Question

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.

Was it helpful?

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.

OTHER TIPS

Java guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right. The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. Java also guarantees that every operand of an operator (except the conditional operators &&, ||, and ?:) appears to be fully evaluated before any part of the operation itself is performed. See Java language specification §15.7 for more details.

C++, on the other hand, happily let's you get away with undefined behavior if the expression is ambiguous because language itself doesn't guarantee any order of evaluation of sub-expressions. See Sequence Point for more details.

In C++ the order of evalulations of subexpressions isn't left-to-right nor right-to-left. It is undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top