Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment operator not working with sizeof [duplicate]

Just wondering why the increment operator is not working in the below code snippet:

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

Output-

a: 10

b: 4

like image 353
user1367292 Avatar asked Dec 27 '12 16:12

user1367292


2 Answers

sizeof does not evaluate its argument. It calculates the argument's size statically at compile-time without causing any code to be executed.

like image 50
sepp2k Avatar answered Oct 07 '22 12:10

sepp2k


When the type of the expression to sizeof is not a variably modified array type, then the expression is not evaluated because the type is completely known at compile time. int has no variably modified parts.

In C++ (up to at least C++11) there are no variably modified types (at least not as in the concept of C - you can argue that new int[a++] uses a variably modified array type; but the type does not escape to any other part of the language. In particular, not to sizeof), so in C++, the expression to sizeof is never evaluated. In C, it is unspecified whether an expression is evaluated if it doesn't influence the size of a variably 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 (from C99 onwards), this may output 11 for a, but it may also output 10, depending on whether the compiler is clever enough to omit evaluating a++, deducing that the sizeof int[10] is computed at compile time.


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

like image 21
Johannes Schaub - litb Avatar answered Oct 07 '22 13:10

Johannes Schaub - litb