How does sizeof wоrk in this case?

Viewed 125

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.

2 Answers

An int is 4 byte long. You are are passing the sizeof operatore an int Array of length 2. To store an int Array of 2 you need 2x4 = 8 Bytes.

++i

increments the value of i from 1 to 2 before it is used. That's why your output is 8 and 2.

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.

Related