Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence, which result is correct? [duplicate]

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?

like image 278
Genzer Avatar asked Apr 06 '11 18:04

Genzer


1 Answers

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.

like image 131
Matthew Flaschen Avatar answered Sep 28 '22 13:09

Matthew Flaschen