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.
c++javaoperator-precedenceundefined-behavior
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.
Best Answer
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§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:
In C, it is undefined behavior to modify a variable twice without a sequence point in between.