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?


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.


Operator precedence governs how operands are grouped together for calculating the result. It doesn't necessarily govern the order of applying side effects.

In C++, the ++ operators will both be calculated before the + operator (although this only makes a difference in the ++x , because the value of x++ is the same as x ). The side effect of incrementing x happens before the next sequence point in C++, and that's all we can say, and the only sequence point in that expression is after it is completely evaluated, including the assignment. Further, the result of modifying an object more than once between sequence points is explicitly undefined according to the Standard.

Given undefined behavior, the typical implementation will do something that depends on the details of how the implementation sequences defined behavior, and so you will often get a consistent result if you stick to one version of one compiler.


It is undefined behaviour in C++. See 5.4 in the standard.

链接地址: http://www.djcxy.com/p/73226.html

上一篇: 何时postincrement i ++得到执行?

下一篇: 运算符优先级,哪个结果是正确的?