问题
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