8

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?

4
  • The issue is not to do with operator precedence. See here for info about C++: stackoverflow.com/questions/4176328/… Commented Apr 6, 2011 at 18:29
  • 1
    Related: stackoverflow.com/questions/4638364/… Commented Apr 6, 2011 at 18:30
  • 1
    This isn't a duplicate of the question people are choosing, since that's about only C++, while this compares to Java. Commented Apr 6, 2011 at 18:47
  • g++ and MSVC give 13, but clang++ for example gives 12. It really is undefined. Commented Apr 6, 2011 at 19:35

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

1 Comment

No, it's undefined. Unspecified behavior is where the implementation has to do something useful but can decide the actual behavior arbitrarily (like deciding whether to calculate f(x) or g(x) in (f(x) + g(x))).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.