Search code examples
carrayssizeof

How does sizeof wоrk in this case?


Look at the following code:

#include <stdio.h>

int main(void) 
{
    int i = 1;
    printf("%lu\n", sizeof(int[++i]));
    printf("%d", i);
}

I was testing the sizeof operator because variable-length array type operands are evaluated — I would be happy if someone gives clarification on this as well but the question is different.

6.5.3.4/2

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined by the type of the operand. The result is an integer. If the type of the operand is a variable-length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

The output of the above code on GCC is as follows:

8
2

Can someone please explain where this 8 comes from? Does the array decay into a pointer? Please also give clarification on the variable-length array part.


Solution

  • At the time int[++i] is evaluated, i initially has the value 1. So int[++i] evaluates to int[2], i.e. an array of int of size 2.

    Assuming an int is 4 bytes on your system, this array is 8 bytes in size.