Question about post-increment operator

大憨熊 提交于 2019-12-24 06:00:07

问题


Why does the following code

int i = 1; 
System.out.print(i += i++);
System.out.print(i);

output 2 two times instead of 3 for the 2nd print?

Could somebody please shed some light on it?

Thanks.


回答1:


If you realise that a++ works as follows (pseudocode):

func ++(ref a)
{
    int b=a;
    a=a+1;
    return b;
}

then it all makes sense.




回答2:


It may seems like i should be 3 in the end.

However, if you look into the statement more closely

i += (i++)

is equal to

i = ( i + (i++) ) 

which is, in this case, 1+1.

The side effect of i++ is i=i+1=1+1=2 as you may have expected, however, the value of i is override after the assignment.




回答3:


I don't know the Java bytecode syntax very well yet but according to me at bytecode level your code would look something like this :

int i = 1;  // iconst_1:    variables { }, stack {1}
            // istore_1:    variables {1}, stack { }
i += i++;   // iload_1:     variables {1}, stack {1}
            // iinc 1, 1:   variables {2}, stack {1}
            // iadd:        variables {2}, stack {2} ...Note that here 1 gets added to the value on stack
            // istore_1:    variables {2}, stack {2} ...Here the variable value will overwrite the stack value

I think this explains the output you are getting pretty well. :-)

Experts, please correct me if I am wrong...




回答4:


I don't think this is an issue with not knowing how the postfix unary operator (expr++) works. It is the order in which the statements are evaluated that is creating the confusion.

int i = 1;
System.out.println(i += i++); // Output: 2

So the last statement is the same as the following two statements in this order:

i++; // i is now 2 for the rest of this statement and the program
i = 1 + 1; // i is assigned again  

So the postfix operator is evaluated first but then the whole line is evaluated but using the previous value of i.

So, to use another example that would make this more clear:

int i = 2;
System.out.println(i += i++); // Output: 4
System.out.println(i); // Output: 4  

And another example:

int i = 2;
System.out.println(i = i + i++ + i--); // Output: 7
System.out.println(i); // Output: 7  

The second line is assigning i. The first i is 2, the next i is also 2, but now the third i is 3 because i++ has changed the value of i. As the case from before, i-- will not have any affect on i because it will get rewritten with i = 2 + 2 + 3.

int i = 1;
System.out.println(i = i++ + i); // Output: 3
System.out.println(i); // Output: 3



回答5:


1 + 1 == 2. 

Therefore:

i + i == 2  

and

i += i == 2

and then

i += i++ == 2

Pretty straight forward.



来源:https://stackoverflow.com/questions/2081013/question-about-post-increment-operator

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