8

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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user1367292
  • 1,029
  • 2
  • 11
  • 13

5 Answers5

11

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

sepp2k
  • 363,768
  • 54
  • 674
  • 675
8

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++].

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • +1: in C++11, 5.3.3p1, "The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, **which is an unevaluated operand** (Clause 5), or a parenthesized type-id." emphasis added. – WhozCraig Dec 27 '12 at 16:39
2

The operand of the sizeof operator is unused, it's not evaluated. This is standard behavior.

1

sizeof is not a function in C.

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

int b = 4
lbonn
  • 2,499
  • 22
  • 32
0

In an unevaluated-context, only the type matters. The same happens when calling functions:

void f();

sizeof(f()); // f not called
David G
  • 94,763
  • 41
  • 167
  • 253