1

why does

int a = 0;
cout<< (++a) + (++a) + (++a) 

show 9 as a result since it should be: 1 + 2 + 3 that is 6

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • 3
    It is a beautiful example of undefined behavior. (++a) + (++a) is UB. – Georgy Firsov Jul 12 '20 at 09:29
  • I don't understand why you don't understand. It's obvious that what is happening in your code is that `a` is being incrementing three times (`a == 3`) and then added three times (`3 + 3 + 3 == 9`). That's what's happening for you, but as already said your code actually has *undefined behaviour* so anything could happen. If the compiler outputs 6 it would be correct, if it outputs 9 it would be correct, if it crashes it would be correct, if it did something else entirely it would be correct. C++ does not define any particular behaviour for this code. – john Jul 12 '20 at 09:43

0 Answers0