++i + ++i
" in two different languages: C and C #. The first, as you know, is compiled into native processor code, and the second, if roughly, works on the basis of a virtual stack machine. And so, consider the examples themselves:# A # 5: int i = 5; cs: 0295 BE0500 mov si, 0005 # A # 6: i = ++ i + ++ i; cs: 0298 46 inc si cs: 0299 46 inc si cs: 029A 8BC6 mov ax, si cs: 029C 03C6 add ax, si cs: 029E 8BF0 mov si, ax # A # 7: printf ("% d \ n", i); cs: 02A0 56 push si cs: 02A1 B8AA00 mov ax, 00AA cs: 02A4 50 push ax cs: 02A5 E8330C call _printf
i
to the SI
register of the x86
. After that, double-incrementing this register, I added it to myself through the AX
battery. As a result, the variable i
becomes equal to 14..method public hidebysig static void Main () cil managed { .entrypoint // Code size 21 (0x15) .maxstack 3 .locals init (int32 V_0) IL_0000: ldc.i4.5 // push 5 5 IL_0001: stloc.0 // i: = pop () null IL_0002: ldloc.0 // push ii IL_0003: ldc.i4.1 // push 1 i, 1 IL_0004: add // push (pop () + pop ()) (i + 1) 6 IL_0005: dup // copy top of stack 6, 6 IL_0006: stloc.0 // i: = pop () // i: = 6 6 IL_0007: ldloc.0 // push i 6, i IL_0008: ldc.i4.1 // push 1 6, i, 1 IL_0009: add // push (pop () + pop ()) 6, (i + 1) i.e. 7 IL_000a: dup // copy tops of stack 6, 7, 7 IL_000b: stloc.0 // i: = pop () // i: = 7 6, 7 IL_000c: add // push (pop () + pop ()) 13 IL_000d: stloc.0 // i: = pop () null IL_000e: ldloc.0 // push ii IL_000f: call void [mscorlib] System.Console :: WriteLine (int32) IL_0014: ret } // end of method Test :: Main
i
, the variable itself and the unit are pushed onto the stack. Then the addition command is executed which, taking two values from the stack and adding, pushes the result back onto the stack. Then duplication of the top of the stack occurs and the value is written back to the variable. Thus, 5 + 1
remains in the stack, i.e. 6. Next, the cycle repeats for another increment: the variable is pushed onto the stack, followed by the unit, the addition, duplication of the vertex occurs, and the result of the second increment is written back into the variable. Now i
will be 7, and 6 from the first case and 7 from the second will remain in the stack. Then the command of addition is executed and the result, now equal to 13, is entered into the variable.Source: https://habr.com/ru/post/88185/
All Articles