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:
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.