SD11 SD11 - 10 months ago 48
C Question

name of structure as the operand of the sizeof

When you define a structure like below

typedef struct num{

int a;
int b;

}A;


Then sizeof(A) is valid, but sizeof(num) isn't. Could anyone please explain the reason why the sizeof operator doesn't accept 'num'?

usr usr
Answer Source

Because num on its own doesn't constitute a type in C (only struct num or its typedef A constitutes the type). So, sizeof fails as its operand is not in either form of that it's defined for:

sizeof unary-expression
sizeof ( type-name ) 

i.e. num is neither a type nor a unary-expression.

So, sizeof(struct num) or sizeof(A) is fine but sizeof(num) isn't.