C # for loop and increment

I find it hard to understand why the next loop prints 0 at each iteration.

for (int i = 0, j = 0; i < 10; i++)
{
    Console.WriteLine(j += j++);
}

Should the j value be increased after each iteration? If you can not explain it?

After positive feedback from @Jon Skeet, I went through parsing the application and was able to how the code behaves at a low level. I added a showdown with my comments.

Thank!!!

    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:             }
+4
source share
1 answer

Should the j value be increased after each iteration?

Nope. The body of your loop 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);

, j ... j 0, 0. j , j++... , .

+14

Source: https://habr.com/ru/post/1664945/


All Articles