Reputation: 425
The code below could not be compiled(GCC). It said that the person and u_type are undeclared. If I use a variable in sizeof(), it is OK. So why need a variable in sizeof(). The GNU C Reference Manual said that sizeof operator can be used with both type and expression.
Thanks,
struct person {
int age;
char *name;
};
union u_type {
int t_int;
double t_double;
};
int main(void) {
printf("size of person is %d\n", sizeof(person));
printf("size of u_type is %d\n", sizeof(u_type));
return 0;
}
Upvotes: 0
Views: 67
Reputation: 29266
There is nothing in your program called person
or u_type
. Sure you have struct person
and union u_type
but there are no typedefs to let you just use person
and u_type
Try sizeof(struct person)
To answer the questions in the comments:
struct person { ... };
Gives you a type: struct person
- where person is a tag. You need to use struct person
to use the type. In this case sizeof(struct person)
.
struct { ... } person;
Gives you a variable called person
that is a struct (but you can't reuse the type). In this case sizeof(person)
The most common use is typedef struct { ... } Person
which gives you a type Person - much like the first case, but you can use Person
instead of struct person
. In this case sizeof(Person)
Upvotes: 2
Reputation: 307
This is because sizeof operator needs something for which it can tell size of. If it is left empty, it would have nothing to review and generate an answer, but because you have used it in the program by passing no arguments, it will give an error because sizeof empty is kind of vague if you understand.
Upvotes: -1