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

梦想的初衷 提交于 2020-01-05 07:30:52

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/48138667/why-i-i-ai-ai-ai-results-in-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!