[英]Why does the loop print 0 at the end?
This is an example I found on a website. 这是我在网站上找到的一个例子。 The result is really different from what I expected. 结果与我的预期完全不同。 But there is no further explain. 但没有进一步的解释。
int num = 0;
for (int i = 0; i < 3; ++i)
{
num += num++;
}
System.out.println(num);
Finally, the result will print 0
. 最后,结果将打印0
。 I am really confused about the operation num += num++
. 我对操作num += num++
感到很困惑。 Can someone explain this? 有人可以解释一下吗?
num++
increments num after
the instruction (it is a post-increment operator). num++
在指令after
递增num(它是一个后递增运算符)。
So num += num++;
所以num += num++;
assigns 0
to num
(num = 0 + 0 + 0). 将0
分配给num
(num = 0 + 0 + 0)。
After the instruction num += num++;
指令后num += num++;
the post increment of num
(that is num++
) has no effect as num
was assigned to another value (that is num += 0
which the result is 0
) . num
的后增量(即num++
)无效,因为num
被分配给另一个值(即num += 0
,结果为0
)。
So num
is valued to 0
. 所以num
的值为0
。 And so on for each iteration. 等等每次迭代。
Replace num += num++
by ++num
that is the pre-increment operator, you will get the result : 3
(as you increment 1 by iteration). 将num += num++
替换为预增量运算符的++num
,您将得到结果: 3
(通过迭代递增1)。
This assignment 这个任务
num += num++;
invokes two different rules in java: one on the left side, one on the right side. 在java中调用两个不同的规则:一个在左侧,一个在右侧。
The right side rule is fairly well known: the value of the post-increment operator is the value of the variable before the increment. 右侧规则是众所周知的:后增量运算符的值是增量前变量的值。 This makes the value of 0++
a zero. 这使得0++
的值为零。
The other rule is a bit more obscure (I was not aware of the left side rule). 另一条规则有点模糊(我不知道左侧规则)。
According to "15.7.1. Evaluate Left-Hand Operand First" in Java Language Specification Java first decides just what gets assigned, and also what is its value . 根据Java语言规范 Java中的“15.7.1。首先评估左手操作数”,Java首先决定分配什么,以及它的价值 。 Then the right side of +=
is computed. 然后计算+=
的右侧。
With these two rules in mind, the assignment above is the equivalent of: 考虑到这两个规则,上面的赋值相当于:
temp1 = num // and will assign to num
temp2 = num // before ++
num = num + 1
num = temp1 + temp2
As you can see, the last line adds the original value of num
(it happens to be 0
) to the value of num
before ++, which ensures that num
does not change. 如您所见,最后一行将num
的原始值(恰好为0
)添加到++之前的num
值,这可确保num
不会更改。 It starts at 0
, it ends with 0
. 它开始于0
,它结束0
。
Suppose that you're now using a pre-increment operator: 假设您现在使用的是预增量运算符:
num += ++num;
Now the situation is sligthly different. 现在情况略有不同。
int temp1 = num // and num will be assigned
int temp2 = num = num + 1
num = temp1 + temp2
The value of num
used in num += xxx
is not the result of ++num
- it is the value we had before ++num
was executed. 的值num
中使用num += xxx
不是的结果++num
-它是我们之前具有的值++num
被处死。
So first iteration we have 0+=1
, second iteration it's 1+=2
and third iteration it's 3+=4
- that's 7
所以第一次迭代我们有0+=1
,第二次迭代它是1+=2
和第三次迭代它是3+=4
- 那是7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.