Search code examples
javac++operator-precedencepost-incrementpre-increment

How does expression evaluation order differ between C++ and Java?


I've had my brain wrinkled from trying to understand the examples on this page: http://answers.yahoo.com/question/index?qid=20091103170907AAxXYG9

More specifically this code:

int j = 4;
cout << j++ << j << ++j << endl;

gives an output: 566

Now this makes sense to me if the expression is evaluated right to left, however in Java a similar expression:

int j = 4;
System.out.print("" + (j++) + (j) + (++j));

gives an output of: 456

Which is more intuitive because this indicates it's been evaluated left to right. Researching this across various sites, it seems that with C++ the behaviour differs between compilers, but I'm still not convinced I understand. What's the explanation for this difference in evaluation between Java and C++? Thanks SO.


Solution

  • When an operation has side effects, C++ relies on sequence points rule to decide when side effects (such as increments, combined assignments, etc.) have to take effect. Logical and-then/or-else (&& and ||) operators, ternary ? question mark operators, and commas create sequence points; +, -, << and so on do not.

    In contrast, Java completes side effects before proceeding with further evaluation.

    When you use an expression with side effects multiple times in the absence of sequence points, the resulting behavior is undefined in C++. Any result is possible, including one that does not make logical sense.