Here is the code compiled in dev c++ windows:
#include <stdio.h>
int main() {
int x = 5;
printf("%d and ", sizeof(x++)); // note 1
printf("%d\n", x); // note 2
return 0;
}
I expect x
to be 6 after executing note 1. However, the output is:
4 and 5
Can anyone explain why x
does not increment after note 1?
sizeof
runs at compile-time, butx++
can only be evaluated at run-time. To solve this, the C++ standard dictates that the operand ofsizeof
is not evaluated (except for VLAs). The C Standard says:From the C99 Standard (the emphasis is mine)
sizeof(foo)
tries really hard to discover the size of an expression at compile time:6.5.3.4:
In short: variable length arrays, run at runtime. (Note: Variable Length Arrays are a specific feature -- not arrays allocated with
malloc(3)
.) Otherwise, only the type of the expression is computed, and that at compile time.As the operand of
sizeof
operator is not evaluated, you can do this:Online demo : http://ideone.com/S8e2Y
That is, you don't need define the function
f
if it is used insizeof
only. This technique is mostly used in C++ template metaprogramming, as even in C++, the operand ofsizeof
is not evaluated.Why does this work? It works because the
sizeof
operator doesn't operate on value, instead it operates on type of the expression. So when you writesizeof(f())
, it operates on the type of the expressionf()
, and which is nothing but the return type of the functionf
. The return type is always same, no matter what value the function would return if it actually executes.In C++, you can even this:
Yet it looks like, in
sizeof
, I'm first creating an instance ofA
, by writingA()
, and then calling the functionf
on the instance, by writingA().f()
, but no such thing happens.Demo : http://ideone.com/egPMi
Here is another topic which explains some other interesting properties of
sizeof
:Note
This answer was merged from a duplicate, which explains the late date.
Original
Except for variable length arrays sizeof does not evaluate its arguments. We can see this from the draft C99 standard section
6.5.3.4
The sizeof operator paragraph 2 which says:A comment(now removed) asked whether something like this would evaluate at run-time:
and indeed it would, something like this would also work (See them both live):
since they are both variable length arrays. Although, I don't see much practical use in either one.
Note, variable length arrays are covered in the draft C99 standard section
6.7.5.2
Array declarators paragraph 4:Update
In C11 the answer changes for the VLA case, in certain cases it is unspecified whether the size expression is evaluated or not. From section
6.7.6.2
Array declarators which says:For example in a case like this (see it live):
The execution cannot happen during compilation. So
++i
/i++
will not happen. Alsosizeof(foo())
will not execute the function but return correct type.