Possible Duplicate:
Undefined behavior and sequence points
What is the value of x
after this code?
int x = 5;
x = ++x + x++;
In Java, the result is 12, but in C++, the result is 13.
I googled the operator precedence of both Java and C++, and they look the same. So why are the results different? Is it because of the compiler?
In Java it's defined to evaluate to 12. It evaluates like:
x = ++x + x++;
x = 6 + x++; // x is now 6
x = 6 + 6; // x is now 7
x = 12 // x is now 12
The left operand of the +
(++x) is completely evaluated before the right due to Evaluate Left-Hand Operand First. See also this previous answer, and this one, on similar topics, with links to the standard.
In C++, it's undefined behavior because you're modifying x three times without an intervening sequence point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With