for (int i = 0; i < 10; i = i++) {
上述循环基本上与以下相同: –
for (int i = 0; i < 10; i = i) {
您的声明的第三部分 – 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
现在,首先将对RHS部分(A B)进行评估,然后将最终结果分配给x。所以,让我们继续前进。
首先评估: –
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步。
现在,转到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 --> 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的第3部分,看看它在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;
我希望这一点清楚。