Unary Operations fused with assignment

余生长醉 提交于 2019-12-10 20:46:43

问题


Doubtful result in the following code:

public static void main (String[] args)
{ 
int i = 2;
i = i+=2 + i++;
System.out.println(i); }

Was expecting 8 as output, as 'i+=2' should update i, but its not behaving so.

Output: 6

I infer that the short-hand assignment operator is returning 4 as expected but not updating the same in variable i. Any explanation will be appreciated.


回答1:


i++ is a postfix increment - it increments i, then essentially returns the old value of i. The equivalent prefix operator, ++i, would return the "updated" value, but that's not what's being used here.

i+=2 works differently however, it's essentially equivalent to i+2, since it does return the updated value.

However, I think where the confusion arises is that you're looking at it like this:

i = (i += 2) + i++;

...which does give your expected result. i+=2 gives 4, and updates i to 4, then i++ returns 4 (instead of 5 since it's a post increment.) However, when you take operator precedence into the equation, Java actually "brackets" it like this by default:

i = i += (2 + i++);

Just to clear up any confusion, Java evaluates it this way because the += operator has least precedence in this example, and therefore the addition expression (+) is calculated first.

This bracketed statement is essentially equivalent to:

i = (i = i + (2 + i++));

Which in turn simplifies to:

i = i + (2 + i++);

So given the above statement, and evaluating from left to right, we first take the value of i (2), and then add to it the value of 2+i++; the latter giving 4 (because of the postfix increment). So our final result is 2+4, which is 6.



来源:https://stackoverflow.com/questions/16360084/unary-operations-fused-with-assignment

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