I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:
What does the following piece of code do:
The output is 9 (try it)
int i = 1;
i += ++i + i++ + ++i;
becomes
i = 1 + 2 + 2 + 4
The code
int i = 1;
i += ++i + i++ + ++i
is equivalent to
int tmp1 = i // 1, +=
i ++; // 2
int tmp2 = i; // 2
int tmp3 = i; // 2
i ++; // 3
i ++; // 4
int tmp4 = i; // 4
i = tmp1 + tmp2 + tmp3 + tmp4; // 9
i += ++i + i++ + ++i;
is the same as i = i + ++i + i++ + ++i;
The right-hand side is calculated from left-to-right, yielding i = 1 + 2 + 2 + 4;
(which yields i = 9
).
You're right regarding the right part evaluation, but you're missing a detail regarding the assignment.
Run this :
i = i++;
or this :
i += i++;
After both operations, i still has its original value.
That's because i is evaluated on the left before the right part of the assignment.
So in your case, you're adding 8 to 1, not to 4.
i += ++i + i++ + ++i
;
i=1
at starti += X
-> i = i + X
-> i = 1 + X
(so lets count X)++i
will be incremented to 2 and return 2
i++
will return 2
and then be incremented to 3++i
will be incremented from 3 to 4 and return 4
X = 2 + 2 + 4 = 8
So i = 1 + 8
-> i=9
You would get 12 if your code would be something like this
int i = 1;
int tmp = ++i + i++ + ++i;
i += tmp;
because then your code would be i=1
, and after calculating tmp i would be i=4
, then i+=tmp
-> i=4+8=12
it's very easy to understand how it works if you imagine it how java stores values in registers! he puts 1 in the first register, and than goes through = sign, and increments the i(++i), so now in i you have 2, and in the second register you have 2, but the first register is not updated, in the third register you'll have 2 and then i is incremented, and then i is incremented and in the last register you'll have 4. So you'll have something like this 1 = 2 + 2 + 4 == 9