0

Could you help me explain this result:

int b = 5, i = 0;
i = ++b + ++b + b++;

The actual result is 21 (run program) In my opinion, the order of calculation is: b++ (posfix): return 5 and b = 6 the first ++b: return 7 and b = 7 the second ++b: return 8 and b = 8 So the resuld should be: i = 7 + 8 + 5 = 20. What wrong with my calculation ? anyone can help.

RHertel
  • 23,412
  • 5
  • 38
  • 64
  • 5
    This is not a matter of operator precendence. It is undefined behavior. – RHertel Aug 11 '21 at 09:41
  • @RHertel, can you explain more detail ? – Trong Hoang bao Aug 11 '21 at 10:28
  • 1
    @TrongHoangbao [See this](https://godbolt.org/z/Tsc7We3Yx). The output is 20. What is the reason for the output being different? See the duplicate link, and it will explain what undefined behavior is. Also, *read the compiler warnings*. If the output were 0, or 20, or 21, or 200, the compiler would be "correct". – PaulMcKenzie Aug 11 '21 at 10:30

0 Answers0