I am totally lost why I get these results:
int i = 1;
int[] a = new int[6];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
a[5] = 5;
i += i + a[i++] + a[i++];
//i is 5
i = 1;
i += i + a[i++] + a[i++] + a[i++];
// i is 8
I (wrongly) thought that there are these options:
i = i(=1) + a[i++]
+ etc - meaning that i = 1 is cached and not
changed then. Expression evaluation order is exactly from left to
right, I guess (?!).i = i(=3) + a[1] + a[2]
now i = 3 and written to leftmost iBut actual results leave me with no clue...
i += i + a[i++] + a[i++];
adds the original value of i to the value of the expression i + a[i++] + a[i++]
and assigns the result to i
.
It's equivalent to
i = i + i + a[i++] + a[i++];
1 + 1 + a[1] + a[2] = 1 + 1 + 1 + 2 = 5
Then you assign 1 to i
and calculate:
i += i + a[i++] + a[i++] + a[i++];
which is equivalent to
i = i + i + a[i++] + a[i++] + a[i++];
1 + 1 + a[1] + a[2] + a[3] = 1 + 1 + 1 + 2 + 3 = 8
The important thing to note is that each a[i++]
increments i
, but accesses the element of a
at the index of the previous value of i
(i.e. the value prior to the increment).
Therefore the first a[i++]
returns a[1]
(even though i
is incremented to 2), the second a[i++]
returns a[2]
(even though i
is incremented to 3
) and the third a[i++]
returns a[3]
(even though i
is incremented to 4
).