-3

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?

wusatosi
  • 579
  • 4
  • 11
  • 7
    `sizeof k+k` = `sizeof(k)+k` = `4 + 1` = `5`; `sizeof k+k` is different to `sizeof(k+k)` – eyllanesc Sep 15 '21 at 05:28
  • I prefer positioning the parenthesis like this: `(sizeof k) + k` ... *some people insist on using parenthesis for the `sizeof` operand... `(sizeof (k)) + k`* – pmg Sep 15 '21 at 11:43

2 Answers2

4

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

Eric Postpischil
  • 168,892
  • 12
  • 149
  • 276
selbie
  • 91,215
  • 14
  • 97
  • 163
  • Precedence determines expression structure, not evaluation priority. A function call has higher precedence than `&&`, but `0 && f()` does not prioritize calling `f` over evaluating `&&`. – Eric Postpischil Sep 15 '21 at 11:41
2

It basically does sizeof(k) + k -> 4 + 1 = 5. See also what-does-sizeof-without-do.

kraego
  • 1,653
  • 1
  • 15
  • 27