views:

445

answers:

4

Possible Duplicate:
How do we explain the result of the expression (++x)+(++x)+(++x)?

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

Which is more correct? Java's result of 12 or C = 13. Or if not a matter of correctness, please elaborate. Thank you.

+4  A: 

In C this is undefined behavior. There is no correct.

JoshD
+14  A: 

There is nothing like more correct. It is actually undefined and its called Sequence Point Error. http://en.wikipedia.org/wiki/Sequence_point

Rohit
Thank you, I'm enlightened by the term Sequence Point Error.
Manny
+1, very nice .
JoshD
It's well-defined in Java.
Matthew Flaschen
+5  A: 

The Java result makes sense to me because the operators give the result you would expect, but no serious program should contain a statement like this.

EDIT: I'm amused that this one sentence response has been my highest scored answer of the evening (compared to the dozen other answers I posted, some with pages of code samples). Such is life.

Tim
+19  A: 

Java guarantees (§15.7.1) that it will be evaluated left-to-right, giving 12. Specifically, ++ has higher precedence that +. So it first binds those, then it associates the addition operations left to right

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

§15.7.1 says the left operand is evaluated first, and §15.7.2 says both operands are evaluated before the operation. So it evaluates like:

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, it is undefined behavior to modify a variable twice without a sequence point in between.

Matthew Flaschen
A small question - is left-to-right really needed here? In this example, can another order give a different result? I suppose it's more relevant to statements like `i = (i*=2) + (i*=3) + (i*=4);`, where order matters.
Kobi
Thanks, @Potatoswatter.
Matthew Flaschen
@Kobi, not really, but I hope explaining simpler cases helps people work up to more complex ones.
Matthew Flaschen
Change it to `++i - ++i - ++i` and left-to-right order becomes very important.
Paul McGuire
Shouldn't the step after `((3 + 4) + (++i))` be `((3 + 4) + 5)`? Since `++` has higher precedence than `+`?
configurator
@config, it's important to distinguish between precedence and order of evaluation. The precedence basically determines where the simulated parentheses are put; order of evaluation is the sequence of actual computations. Order of evaluation is in [§15.7](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7). Because of [§15.7.1](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7.1) the left operand `(3 + 4)` must be evaluated before the right operand `(++i)` (of the outer +).
Matthew Flaschen
@Matthew: Oh, of course. Makes perfect sense.
configurator