一元运算与任务融合 [英] Unary Operations fused with assignment
问题描述
可疑的结果是以下代码:
Doubtful result in the following code:
public static void main (String[] args)
{
int i = 2;
i = i+=2 + i++;
System.out.println(i); }
期望输出为 8 ,因为'i + = 2'应该 update i,但其行为并非如此.
Was expecting 8 as output, as 'i+=2' should update i, but its not behaving so.
输出:6
Output: 6
我推断速记赋值运算符正在按预期返回 4 ,但没有更新变量i中的相同值.任何解释将不胜感激.
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.
推荐答案
i++
是后缀增量-它递增i,然后本质上返回i的旧值.等效的前缀运算符++i
将返回更新的"值,但这不是这里使用的值.
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
的工作原理不同,它基本上等同于i+2
,因为它确实返回更新后的值.
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++;
... 确实给出的预期结果. i+=2
给出4,并将i
更新为4,然后i++
返回4(因为它是后增量,而不是5).但是,当您将运算符优先级放到公式中时,Java实际上像这样括弧"默认情况下:
...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++);
只是为了消除任何混乱,Java以此方式进行评估,因为+=
运算符在此示例中优先级最低,因此,首先计算加法表达式(+
).
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++));
依次简化为:
i = i + (2 + i++);
因此,根据上述陈述,并从左至右进行评估,我们首先获取i(2)的值,然后将2+i++
的值添加到其中;后者给出4(因为后缀增加).所以我们的最终结果是2 + 4,即6.
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.
这篇关于一元运算与任务融合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!