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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…