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: }