【C】Pointer (12) Incomplete Type: Union with Uncertain Enumerator List
※ 日本語ページはこちら
A type specifier of the form enum identifier without an enumerator list shall only appear after the type it specifies is complete.
Programs which includes union without an enumerator list, incomplete-union.c
#include <stdio.h>
int main (void)
{
union union1 u_test1;
union union2 u_test2;
printf ("size of union1 is %d\n", sizeof(u_test1));
union union3 {
char c ;
int i ;
} u_test3 ;
union union2 { char c; int i;} u_test2;
printf ("size of union2 is %ld\n", sizeof(u_test2));
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
u_test3.c = 10;
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
u_test3.i = 260;
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
return 0;
}
Compile result of incomplete-union.c
$ gcc incomplete-union.c
incomplete-union.c: In function ‘main’:
incomplete-union.c:5:15: error: storage size of ‘u_test1’ isn’t known
union union1 u_test1;
^
incomplete-union.c:6:15: error: storage size of ‘u_test2’ isn’t known
union union2 u_test2;
^
Programs which does not include error generating parts, incomplete-union2.c
#include <stdio.h>
int main (void)
{
/*
union union1 u_test1;
union union2 u_test2;
printf ("size of union1 is %d\n", sizeof(u_test1));
*/
union union3 {
char c ;
int i ;
} u_test3 ;
union union2 { char c; int i;} u_test2;
printf ("size of union2 is %ld\n", sizeof(u_test2));
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
u_test3.c = 10;
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
u_test3.i = 260;
printf ("size of union3 is %ld\n", sizeof(u_test3));
printf ("u_test3.c is %d\n", u_test3.c);
printf ("u_test3.i is %d\n", u_test3.i);
return 0;
}
Compile result and execution result incomplete-union2.c
$ gcc incomplete-union2.c
demo@ubuntu:~/SelfStudy/c/pointers/ImcompleteType/enumarator$ ./a.out
size of union2 is 4
size of union3 is 4
u_test3.c is -64
u_test3.i is -396685376
size of union3 is 4
u_test3.c is 10
u_test3.i is -396685558
size of union3 is 4
u_test3.c is 4
u_test3.i is 260
You can see when the type is defined in using union.
That’s all for this time.