后增量运算符不在for循环中递增

emk*_*a86 21 java loops for-loop infinite-loop post-increment

我正在做一些关于Java的研究,发现这很令人困惑:

for (int i = 0; i < 10; i = i++) {
  System.err.print("hoo... ");
}
Run Code Online (Sandbox Code Playgroud)

这是永无止境的循环!

任何人都有很好的解释为何会发生这样的事情

Roh*_*ain 39

for (int i = 0; i < 10; i = i++) {
Run Code Online (Sandbox Code Playgroud)

上述循环基本相同: -

for (int i = 0; i < 10; i = i) {
Run Code Online (Sandbox Code Playgroud)

3 你的一部分for声明- i = i++,被评估为: -

int oldValue = i; 
i = i + 1;
i = oldValue;  // 3rd Step 
Run Code Online (Sandbox Code Playgroud)

你需要从那里删除作业,使它工作: -

for (int i = 0; i < 10; i++) {
Run Code Online (Sandbox Code Playgroud)

(根据评论的OP请求)

行为x = 1; x = x++ + x++;: -

就您在评论中指定的问题而言,以下表达式的结果如下: -

x = 1; 
x = x++ + x++;
Run Code Online (Sandbox Code Playgroud)

获得如下: -

让我们标记第二个陈述的不同部分: -

x = x++ + x++;
R    A     B
Run Code Online (Sandbox Code Playgroud)

现在,首先(A + B)评估RHS部分,然后将最终结果分配给x.那么,让我们继续前进.

首先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.
Run Code Online (Sandbox Code Playgroud)

现在,由于没有在这里完成Ato 的分配R,所以不执行第3步.

现在,转向B评估: -

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.
Run Code Online (Sandbox Code Playgroud)

现在,获得的价值x++ + x++,我们需要做的,我们在评价还剩下最后的分配AB,因为现在是在被分配的值x.为此,我们需要更换: -

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. **/
Run Code Online (Sandbox Code Playgroud)

那么x = x++ + x++,变成: -

x = old1 + old2;
  = 1 + 2;
  = 3;  // Hence the answer
Run Code Online (Sandbox Code Playgroud)

分解第3部分x = x++,看看它是如何工作的x = x++ + x++情况: -

想知道为什么更换为已完成A --> old1,而不是x --> old1,如在案件x = x++.

深入了解x = x++部分,特别是最后一项任务: -

x = oldValue;
Run Code Online (Sandbox Code Playgroud)

如果您考虑x++A这里,那么上述任务可以分解为以下步骤: -

A = oldValue;
x = A;
Run Code Online (Sandbox Code Playgroud)

现在,对于当前的问题,它与: -

A = old1;
B = old2;
x = A + B;
Run Code Online (Sandbox Code Playgroud)

我希望这说清楚.

  • 这是解释`i = i ++`和普通`i ++`之间区别的唯一答案. (2认同)
  • 对此感到好奇,并用Google搜索,解释为什么`i = i ++`不起作用https://www.coderanch.com/how-to/java/PostIncrementOperatorAndAssignment (2认同)

Ser*_*nov 8

你正在使用post-increment : i = i++;,它意味着这样的事情:

temp = i;
i = i + 1;
i = temp;
Run Code Online (Sandbox Code Playgroud)

因为15.14.2 Postfix Increment Operator ++:

后缀增量表达式的值是存储新值之前的变量值.

这就是你有旧价值的原因.

For-loop完成权限:

for (int i = 0; i < 10; i++) {
  System.err.print("hoo... ");
}
Run Code Online (Sandbox Code Playgroud)