Priority operator whose 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 was looking for the priority of both Java and C ++ operators and they look the same. So why are the results different? Is it because of the compiler?

+8
java c ++ operator-precedence
source share
3 answers

In Java, it is defined to evaluate to 12. It evaluates to:

 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 + (++ x) is fully evaluated before the right due to Rate the first operand of the left hand . See also this previous answer and this one , on similar topics, with links to the standard.

In C ++, this behavior is undefined because you change x three times without an intermediate point in the sequence .

+21
source share

This behavior is undefined in C ++ . See 5.4 in the standard.

0
source share

Operator priority determines how the operands are grouped together to calculate the result. This does not necessarily determine the use of side effects.

In C ++, ++ operators will both be evaluated before the + operator (although this only makes a difference in ++x , because the value of x++ same as x ). The side effect of incrementing x occurs up to the next point of the sequence in C ++ and that all we can say is the only point of the sequence in this expression after a complete evaluation, including purpose. In addition, the result of modifying an object more than once between points in a sequence is clearly undefined in accordance with the standard.

Given undefined behavior, a typical implementation will do something that depends on the details of how certain implementation sequences determine the behavior, and therefore you often get consistent results if you stick to the same version of a single compiler.

0
source share

All Articles