开发者

Using ++ inside the sizeof keyword [duplicate]

This question already has answers here: Closed 11 years ago.

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:

Using ++ inside the sizeof keyword [duplicate]

As you can see in the marked line, the size of the integer (4) is already there and just loaded into i. It is not evaluated or even calculated when the program runs.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜