for (int i = 0; i < 10; i = i++) {上面的循环与以下内容基本相同:-
for (int i = 0; i < 10; i = i) {3 次你的一部分
for声明-
i = i++,被评估为: -
int oldValue = i; i = i + 1;i = oldValue; // 3rd Step
您需要从此处删除分配,以使其起作用:-
for (int i = 0; i < 10; i++) {(根据评论的OP请求)
的行为x = 1; x = x++ + x++;
:-
就注释中指定的问题而言,以下表达式的结果:-
x = 1; x = x++ + x++;
获得如下:-
让我们标记第二条语句的不同部分:-
x = x++ + x++;R A B
现在,首先
(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.
现在,由于此处未完成
Ato 的分配
R,因此不会执行第三步。
现在,进行
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.
现在,要获取的值
x++ + x++,我们需要完成在
A和的求值中剩下的最后一个赋值
B,因为现在是在中赋值
x。为此,我们需要替换:-
A --> old1B --> old2 // The last assignment of both the evaluation. (A and B)
因此
x = x++ + x++,变为:-
x = old1 + old2; = 1 + 2; = 3; // Hence the answer
将的第3部分分解x = x++
,x = x++ + x++
以防万一:
想知道为什么更换完成作为
A --> old1和不
x --> old1作为的情况下
x = x++。
深入研究
x = x++零件,特别是最后一个作业:-
x = oldValue;
如果您认为
x++在
A这里,则可以将以上分配分为以下步骤:-
A = oldValue;x = A;
现在,对于当前问题,它与:-
A = old1;B = old2;x = A + B;
我希望这一点很清楚。



