Increment statement does not work with sizeof

Possible duplicate:
Why doesn't sizeof (x ++) increase x?

Just wondering why the increment operator doesn't work in the code snippet below:

int main() { int a = 10; int b = sizeof(a++); cout<<"a: "<<a<<endl; cout<<"b: "<<b<<endl; return 0; } 

Output -

a: 10

b: 4

+8
c ++ operators sizeof
source share
5 answers

sizeof does not evaluate its argument. It calculates the size of the argument statically at compile time, without invoking any code to execute.

+10
source share

If the typeof expression sizeof is not a modified array type, then the expression is not evaluated because the type is fully known at compile time. int has no modified parts.

In C ++ (until at least C ++ 11) there are no changed types (at least not like in the C concept), you can argue that new int[a++] uses a variable array type, but the type do not run to any other part of the language, in particular, not to sizeof ), therefore, in C ++, the expression sizeof is never evaluated. C does not indicate whether an expression is evaluated if it does not affect the size of the modified array type. for example

 int main() { int a = 10; int b = sizeof(int[a++ ? 1 : 1]); cout<<"a: "<<a<<endl; cout<<"b: "<<b<<endl; return 0; } 

In C (starting with C99), this can output 11 for a , but it can also output 10 , depending on whether the compiler is sufficiently equipped to omit the a++ score, deducing that sizeof int[10] computed at compile time.


Footnote: mutable array types are also called VLA types (variable length arrays). In short, a modified type with a variable type is a type that is either a VLA type or a type that depends on one. For example int(*)[a++] .

+8
source share

The operand of the sizeof operator is not used; it is not evaluated. This is standard behavior.

+2
source share

sizeof is not a function in C.

Its argument is really not evaluated, only its type is, and this is done at compile time. In your code, the assignment is equivalent (in your architecture):

 int b = 4 
+1
source share

In an invaluable context, only type matters. The same thing happens when calling functions:

 void f(); sizeof(f()); // f not called 
0
source share

All Articles