Manny
Manny

Reputation: 6287

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

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.

Upvotes: 7

Views: 8971

Answers (4)

Tim M.
Tim M.

Reputation: 54377

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.

Upvotes: 7

JoshD
JoshD

Reputation: 12814

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

Upvotes: 5

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

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.

Upvotes: 29

Rohit
Rohit

Reputation: 525

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

Upvotes: 18

Related Questions