Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
Chironex Avatar asked Jun 21 '12 19:06

Chironex


People also ask

What is the order of evaluation in C programming language?

Only the sequential-evaluation ( , ), logical-AND ( && ), logical-OR ( || ), conditional-expression ( ? : ), and function-call operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands.

How are expressions evaluated in Java?

Java applications process data by evaluating expressions, which are combinations of literals, method calls, variable names, and operators. Evaluating an expression typically produces a new value, which can be stored in a variable, used to make a decision, and so on.

What is the order of evaluation in the expression?

"Order of evaluation" refers to when different subexpressions within the same expression are evaulated relative to each other. you have the usual precedence rules between multiplication and addition.

What is the difference between Java expression and statement?

Variable declarations and assignments, such as those in the previous section, are statements, as are the basic language structures like conditionals and loops. Expressions describe values; an expression is evaluated to produce a result, to be used as part of another expression or in a statement.


1 Answers

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.

like image 164
Sergey Kalinichenko Avatar answered Sep 30 '22 20:09

Sergey Kalinichenko