Search code examples
javaincrementoperator-precedence

Why i += i + a[i++] + a[i++] + a[i++] results in 8?


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:

  1. 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 (?!).
  2. i is increased, which results (for first example) in i = i(=3) + a[1] + a[2] now i = 3 and written to leftmost i
  3. 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...


Solution

  • 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).