[英]C# for loop and post increment
I'm having a hard time understanding why the following loop prints 0 on each iteration. 我很难理解为什么以下循环在每次迭代时打印0。
for (int i = 0, j = 0; i < 10; i++)
{
Console.WriteLine(j += j++);
}
Shouldn't the value of j increase after each iteration? 每次迭代后,j的值不应该增加吗? If not can you please explain?
如果没有,请你解释一下吗?
After positive feed back from @Jon Skeet I stepped through the disassembly of the statement and was able how the code was behaving at a low level. 在从@Jon Skeet获得正反馈之后,我逐步完成了对语句的反汇编,并且能够解释代码在低级别的行为。 I have added the disassembly with my comments.
我添加了反汇编和我的评论。
Thanks!!! 谢谢!!!
54: Console.WriteLine(j += j++);
0000004f mov eax,dword ptr [ebp-40h] /* [ebp-40h] == 0 move to eax */
00000052 mov dword ptr [ebp-48h],eax /* eax == 0 move to [ebp-48h] */
00000055 mov eax,dword ptr [ebp-40h] /* [ebp-40h] move to eax == 0 */
00000058 mov dword ptr [ebp-4Ch],eax /* eax move to [ebp-4Ch] == 0 */
0000005b inc dword ptr [ebp-40h] /* increment [ebp-40h]== 1*/
0000005e mov eax,dword ptr [ebp-48h] /* [ebp-48h] move to eax == 0 */
00000061 add eax,dword ptr [ebp-4Ch] /* (eax == 0 + [ebp-4Ch]) eax == 0 */
00000064 mov dword ptr [ebp-40h],eax /* eax == 0 move to [ebp-40h] */
00000067 mov ecx,dword ptr [ebp-40h] /* [ebp-40h] move to ecx == 0 */
0000006a call 71DF1E00 /* System.Console.WriteLine */
0000006f nop
55: }
Shouldn't the value of j increase after each iteration?
每次迭代后,j的值不应该增加吗?
Nope. 不。 Your loop body is somewhat equivalent to this:
你的循环体有点等同于:
int tmp1 = j; // Evaluate LHS of +=
int tmp2 = j; // Result of j++ is the value *before* the increment
j++;
j = tmp1 + tmp2; // This is j += j++, basically
Console.WriteLine(j);
So basically, you're doubling j
on each iteration... but j
is 0 to start with, so it stays as 0. If you want to just increment j
on each iteration, just use j++
... but ideally do it as a statement on its own, rather than using it as an expression within a bigger statement. 所以基本上,你在每次迭代时加倍
j
...但j
开始时为0,所以它保持为0.如果你想在每次迭代时只增加j
,只需使用j++
...但理想情况下这样做一个声明本身,而不是在更大的声明中使用它作为表达。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.