9

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 question: why is the output for i equal to 5, not 6? Is the ++ simply disregarded? What's going on here? Thanks!

Community
  • 1
  • 1
BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84

5 Answers5

14

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.

3

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: enter image description here 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.

Cees Meijer
  • 742
  • 2
  • 8
  • 23
1

Yes, inside sizeof is only evaluated for the type.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
1

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.

Pih
  • 2,282
  • 15
  • 20
1

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.

Aamir
  • 14,882
  • 6
  • 45
  • 69