Need explanation why this code results in 4240 and 3414. How do incrementors parse? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Need explanation why this code results in 4240 and 3414. How do incrementors parse?

int x = 0, y = 0; cout << ++x << x++ << ++x << x++ << endl; cout << y++ << ++y << y++ << ++y;

28th Mar 2017, 8:02 PM
Magne Tufte Bøyum
Magne Tufte Bøyum - avatar
2 Answers
+ 6
Was this a challenge question? If so, it should be removed, because this is an example of undefined behavior. There are no guarantees on how this will be evaluated, because it is illegal to modify a variable more than once within the same sequence point. What you have (for x) is equivalent to this: cout.operator<<(++x).operator<<(x++).operator<<(++x).operator<<(x++); The compiler can decide to evaluate the arguments in any order it wants. It's the same with any other function call. Compiled with MSVC++ in debug mode, it outputs 4240. But compiled in release mode, it outputs 2130! You can't rely on any consistent output (at least, not across compilers); that's why it's called undefined behavior.
28th Mar 2017, 8:50 PM
Squidy
Squidy - avatar
+ 4
Already posted this in another thread today, but it is still worth a read: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points
28th Mar 2017, 9:04 PM
Tob
Tob - avatar