++ i ++ ++ i ++ ++ i in Java vs C

Possible duplicate:
How to explain the result of the expression (++ x) + (++ x) + (++ x)?

int i=2; i = ++i + ++i + ++i; 

Which is more true? The result is Java 12 or C = 13. Or, if not a question of correctness, please clarify. Thanks.

+5
java c undefined-behavior order-of-evaluation
source share
4 answers

There is nothing more correct. It is actually undefined and its called sequence error. http://en.wikipedia.org/wiki/Sequence_point

+16
source share

Java guarantees ( ยง15.7.1 ) that it will be evaluated from left to right, giving 12. In particular, ++ has a higher priority than + . Therefore, he first links them, then compares the add operations from left to right

 i = (((++i) + (++i)) + (++i)); 

In ยง15.7.1 it is said that the first operand is evaluated first, and ยง15.7.2 says that both operands are evaluated before the operation. Therefore, he evaluates as:

 i = (((++i) + (++i)) + (++i)); i = ((3 + (++i)) + (++i)); // i = 3; i = ((3 + 4) + (++i)); // i = 4; i = (7 + (++i)); // i = 4; i = (7 + 5); // i = 5; i = 12; 

In C, this behavior is undefined to change a variable twice without a sequence point between them.

+26
source share

The Java result makes sense to me because the operators give the result you expect, but no serious program should contain such an operator.

EDIT: It amazes me that this answer in one sentence was my highest typed answer of the evening (compared to the dozen other answers I posted, some with code sample pages). That is life.

+5
source share

In C, this behavior is undefined. Wrong.

+4
source share

All Articles