Search code examples
csizeof

Why sizeof 1+1 is 5?


I am on gcc version 10.3.0 for Ubuntu. I am learning how sizeof expression means in C. I tried:

int k = 1;
sizeof k+k;

Which returns 5, the same goes to sizeof 1+1, which differs from sizeof(int)(4).

Shouldn't this sizeof operation evaluates to sizeof(int), which evaluates to a 4? Does this mean that during an addition, the int grows to a 5-byte long data structure?


Solution

  • Just like multiplication/division have a higher precedence (evaluation priority) than addition/subtraction in an algebra expression, C/C++ has operator precedence as well.

    sizeof is just another operator. And its operator precedence is 2 levels above addition/subtraction operators.

    So it evaluates sizeof k + k the same as (sizeof k) + k instead of sizeof(k+k)

    enter image description here