Incrementor logic

Quoting Java Language Specification, 15.7 Evaluation Order:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

If the operator is a compound-assignment operator (ยง15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable’s value for use in the implied binary operation.

So, essentially, i += ++i will remember the old value of i on the left side, before evaluating the right side.

Remember, evaluation order of operands and precedence of operators are two different things.

Showing evaluation order, step by step, with saved value in {braces}:

int i = 0;
i    = i    += (++i + (i    += 2 + --i) - ++i); // i = 0
i{0} = i    += (++i + (i    += 2 + --i) - ++i); // i = 0
i{0} = i{0} += (++i + (i    += 2 + --i) - ++i); // i = 0
i{0} = i{0} += (1   + (i    += 2 + --i) - ++i); // i = 1
i{0} = i{0} += (1   + (i{1} += 2 + --i) - ++i); // i = 1
i{0} = i{0} += (1   + (i{1} += 2 + 0  ) - ++i); // i = 0
i{0} = i{0} += (1   + (i{1} += 2      ) - ++i); // i = 0
i{0} = i{0} += (1   + 3                 - ++i); // i = 3
i{0} = i{0} += (4                       - ++i); // i = 3
i{0} = i{0} += (4                       - 4  ); // i = 4
i{0} = i{0} += 0                              ; // i = 4
i{0} = 0                                      ; // i = 0
0                                             ; // i = 0

Followup to edits to question

If we name the initial value I and the constant N:

int i = I;
i = i += (++i + (i += N + --i) - ++i);

Then we can see that the values are:

i{I} = i{I} += ((I+1) + (i{I+1} += N + I) - ((I+1+N+I)+1));
i{I} = i{I} += (I + 1 + (I + 1 + N + I) - (I + 1 + N + I + 1));
i{I} = i{I} += (I + 1 + I + 1 + N + I - I - 1 - N - I - 1);
i{I} = i{I} += I;
i{I} = I + I;
i = 2 * I;

Leave a Comment