Search code examples
javac++operator-precedence

Operator precedence, which result is correct?


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?


Solution

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