[Solved] Difference between += 1 and ++ as executed by computer?


For many compilers, these will be identical. (Note that I said many compilers – see my disclaimer below). For example, for the following C++ code, both Test 1 and Test 2 will result in the same assembly language:

int main()
{
    int test = 0;

    // Test 1
    test++;

    // Test 2
    test += 1;

    return 0;
}

Many compilers (including Visual Studio) can be configured to show the resulting assembly language, which is the best way to settle questions like this. For example, in Visual Studio, I right-clicked on the project file, went to “Properties”, and did the following:
enter image description here

In this case, as shown below, Visual Studio does, in fact, compile them to the same assembly language:

; Line 8
    push    ebp
    mov ebp, esp
    sub esp, 204                ; 000000ccH
    push    ebx
    push    esi
    push    edi
    lea edi, DWORD PTR [ebp-204]
    mov ecx, 51                 ; 00000033H
    mov eax, -858993460             ; ccccccccH
    rep stosd
; Line 9
    mov DWORD PTR _test$[ebp], 0
; Line 12 - this is Test 1
    mov eax, DWORD PTR _test$[ebp]
    add eax, 1
    mov DWORD PTR _test$[ebp], eax
; Line 15 - This is Test 2 - note that the assembly is identical
    mov eax, DWORD PTR _test$[ebp]
    add eax, 1
    mov DWORD PTR _test$[ebp], eax
; Line 17
    xor eax, eax
; Line 18
    pop edi
    pop esi
    pop ebx
    mov esp, ebp
    pop ebp
    ret 0
_main   ENDP
_TEXT   ENDS
END

Interestingly enough, its C# compiler also produces the same MSIL (which is C#’s “equivalent” of assembly language) for similar C# code, so this apparently holds across multiple languages as well.

By the way, if you’re using another compiler like gcc, you can follow the directions here to get assembly language output. According to the accepted answer, you should use the -S option, like the following:

gcc -S helloworld.c

If you’re writing in Java and would like to do something similar, you can follow these directions to use javap to get the bytecode, which is Java’s “equivalent” of assembly language, so to speak.

Also of interest, since this question originally asked about Java as well as C++, this question discusses the relationship between Java code, bytecode, and the eventual machine code (if any).

Caution: Different compilers may produce different assembly language, especially if you’re compiling for different processors and platforms. Whether or not you have optimization turned on can also affect things. So, strictly speaking, the fact that Visual Studio is “smart enough” to know that those two statements “mean” the same thing doesn’t necessarily mean that all compilers for all possible platforms will be that smart.

2

solved Difference between += 1 and ++ as executed by computer?