Using ++ inside the sizeof keyword [duplicate]
Possible Duplicate:
what's the mechanism of sizeof() in C/C++?
Hi,
I'm a TA for a university, and recently, I showed my undergraduate students the following C code from a C puzzle I found:
int i = 5;
int j = sizeof(i++);
printf("%d\n%d\n", i, j);
I just have one que开发者_运维技巧stion: why is the output for i equal to 5, not 6? Is the ++ simply disregarded? What's going on here? Thanks!
The expression in a sizeof is not evaluated - only its type is used. In this case, the type is int, the result of what i++ would produce if it were evaluated. This behavior is necessary, as sizeof is actually a compile-time operation (so its result can be used for things like sizing arrays), not a run-time one.
The sizeof operator is evaluated at compile-time. sizeof(i++) basically reads to the compiler as sizeof(int) (discarding the ++).
To demonstrate this you can look at the assembly view of your little program:
Yes, inside sizeof
is only evaluated for the type.
The main reason is that sizeof
is not a function
, it is an operator
. And it is mostly evaluated at compile-time unless there is a variable length array. Since int
's size can be evaluated at compile-time, therefore, it returns 4
.
why is the output for i equal to 5, not 6?
sizeof does not evaluate the expression inside it, only the type.
What we have keep in mind is that sizeof is not a function but a compile time operator, so, it is impossible for it evaluate its content.
精彩评论