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 is increased, which results (for first example) in
i = i(=3) + a[1] + a[2]
now i = 3 and written to leftmost i
- value from rightmost a[THIS_VALUE] is substituted into leftmost i, and last increment is never made.
But 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
).
This important to notice differences between i++ and ++i, when you use i++ it use i value to calculate the operation and then increment i, but when you are using ++i it increment i and the calculate the operation.
it also worth mentioning that i+=X is equal to i = i + X.
So
i += i + a[i++] + a[i++];
is equal to
i = i + i + a[i++] + a[i++]
for i = 1 it is
i = 1 + 1 + a[1] + a[2]
which with your initialisation it will be :
i = 1 + 1 + 1 + 2
and thats how you get i = 5. and same for next line.
Its quite easy acutally, your using post increment. Post increment increments the value after the expression was executed, versus pre which increments before the expression is executed. So i += i + a[i++] + a[i++] + a[i++];
, is 1 += 1 + 1 + 2 + 3, the first access, uses 1, then increment, next access uses two then increment then last access uses three.