I'm having a hard time understanding why the following loop prints 0 on each iteration.
for (int i = 0, j = 0; i < 10; i++)
{
Console.WriteLine(j += j++);
}
Shouldn't the value of j increase after each iteration? 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. 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?
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.
See more on this question at Stackoverflow