0

Hello I have this simple example:

int x = 5;
int y = ++x + ++x;

Is it well-defined or undefined behavior?

Because I see that y will hold 7 + 6 or 6 + 7 and it is the same result.

Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 1
    Yes, undefined. Don't modify the same variable in a given statement unless the modifications are separated by a sequence point (e.g. the `,` operator, or non-overloaded `&&` or `||`) – Cruz Jean Jan 10 '20 at 18:49
  • 6
    Does this answer your question? [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – Algirdas Preidžius Jan 10 '20 at 18:50
  • Yes, it's UB, unsequenced modifications... – anastaciu Jan 10 '20 at 18:51
  • I think it's actually unspecified behavior, but it's definitely either that or UB. See Algirdas' linked question. –  Jan 10 '20 at 18:56
  • Let me throw another monkey wrench into the mix. It's something I'd heard many years ago, before massive parallelism became widely available. Suppose you have hundreds of computers working under automatic optimization, and the system throws the first half of the expression to Node A, which takes 5 and increments it to 6, but it also throws the second half of the expression to Node B, which does exact same thing at the exact same time. So then Node C aggregates the two sub-expressions and adds 6 to 6 resulting in 12. Given how this is _undefined_ anyway, this result actually is "correct". – UncaAlby Jan 10 '20 at 18:59
  • @CruzJean C++17 actually added some new "sequence points" for several operators, but not for `+`. Also, function arguments are now indeterminately sequenced instead of unsequenced. – aschepler Jan 10 '20 at 19:12

0 Answers0