后增量运算符不在 for 循环中递增 [英] Post increment operator not incrementing in for loop
问题描述
我正在做一些关于 Java 的研究,发现这很令人困惑:
I'm doing some research about Java and find this very confusing:
for (int i = 0; i < 10; i = i++) {
System.err.print("hoo... ");
}
这是永无止境的循环!
有人能很好地解释为什么会发生这样的事情吗?
Anybody has good explanation why such thing happens?
推荐答案
for (int i = 0; i < 10; i = i++) {
上面的循环本质上是一样的:-
The above loop is essentially the same as: -
for (int i = 0; i < 10; i = i) {
for
语句的第 3rd 部分 - i = i++
,被评估为: -
the 3rd part of your for
statement - i = i++
, is evaluated as: -
int oldValue = i;
i = i + 1;
i = oldValue; // 3rd Step
<小时>
您需要从那里删除分配,以使其工作:-
You need to remove the assignment from there, to make it work: -
for (int i = 0; i < 10; i++) {
<小时>
(根据评论的 OP 请求)
(On OP request from Comments)
就您在评论中指定的问题而言,以下表达式的结果:-
As far as your issue as specified in the comment is concerned, the result of the following expression: -
x = 1;
x = x++ + x++;
获得如下:-
让我们标记第二个语句的不同部分:-
Let's mark different parts of the second statement: -
x = x++ + x++;
R A B
现在,首先将评估 RHS 部分 (A + B)
,然后将最终结果分配给 x
.所以,让我们继续前进.
Now, first the RHS part (A + B)
will be evaluated, and then the final result will be assignmed to x
. So, let's move ahead.
第一个 A
被评估:-
old1 = x; // `old1 becomes 1`
x = x + 1; // Increment `x`. `x becomes 2`
//x = old1; // This will not be done. As the value has not been assigned back yet.
现在,由于 A
到 R
的赋值没有在这里完成,所以不执行第 3 步.
Now, since the assignment of A
to R
is not done here, the 3rd step is not performed.
现在,转到 B
评估:-
Now, move to B
evaluation: -
old2 = x; // old2 becomes 2. (Since `x` is 2, from the evaluation of `A`)
x = x + 1; // increment `x`. `x becomes 3`.
// x = old2; // This will again not be done here.
现在,为了获得x++ + x++
的值,我们需要做我们在A
和B的评估中留下的最后一个赋值code>,因为现在是在
x
中分配的值.为此,我们需要替换:-
Now, to get the value of x++ + x++
, we need to do the last assignment that we left in the evaluation of A
and B
, because now is the value being assigned in x
. For that, we need to replace: -
A --> old1
B --> old2 // The last assignment of both the evaluation. (A and B)
/** See Break up `x = old1;` towards the end, to understand how it's equivalent to `A = old1; in case of `x = x++`, considering `x++ <==> A` in this case. **/
所以,x = x++ + x++
,变成:-
x = old1 + old2;
= 1 + 2;
= 3; // Hence the answer
<小时>
分解x = x++
的第三部分,看看它在x = x++ + x++
情况下是如何工作的:-
想知道为什么替换为 A -->old1
而不是 x -->old1
,如 x = x++
的情况.
Break up of 3rd part of x = x++
, to see how it works in x = x++ + x++
case: -
Wonder why the replacement is done as A --> old1
and not x --> old1
, as in case of x = x++
.
深入查看x = x++
部分,特别是最后一个赋值:-
Take a deep look at x = x++
part, specially the last assignment: -
x = oldValue;
如果你认为这里的 x++
是 A
,那么上面的赋值可以分解为以下步骤:-
if you consider x++
to be A
here, then the above assignment can be broken into these steps: -
A = oldValue;
x = A;
现在,对于当前的问题,它是一样的:-
Now, for the current problem, it is same as: -
A = old1;
B = old2;
x = A + B;
我希望这能说清楚.
这篇关于后增量运算符不在 for 循环中递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!