The compiler should create the same assembly for 1 and 2, and it can expand the loop in option 3. When you come across similar questions, a useful tool that you can use to empirically test what happens is to view the assembled assembly by the compiler. In g ++, this can be achieved with the -S switch.
For example, both options 1 and 2 create this assembler when compiled using the g++ -S inc.cpp (using g ++ 4.5.2)
main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 movq %rsp, %rbp .cfi_offset 6, -16 .cfi_def_cfa_register 6 addl $5, -4(%rbp) movl $0, %eax leave .cfi_def_cfa 7, 8 ret .cfi_endproc
g ++ creates a significantly less efficient assembler for option 3:
main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 movq %rsp, %rbp .cfi_offset 6, -16 .cfi_def_cfa_register 6 movl $0, -8(%rbp) jmp .L2 .L3: addl $1, -4(%rbp) addl $1, -8(%rbp) .L2: cmpl $4, -8(%rbp) setle %al testb %al, %al jne .L3 movl $0, %eax leave .cfi_def_cfa 7, 8 ret .cfi_endproc
But with optimization on (even -O1) g ++ produces this for all 3 options:
main: .LFB0: .cfi_startproc leal 5(%rdi), %eax ret .cfi_endproc
g ++ not only expands the loop in option 3, but also uses the lea instruction to add to a single command instead of faffing about with mov .
Thus, g ++ will always create the same assembly for options 1 and 2. g ++ will create the same assembly for all 3 options only if you explicitly enable optimization (this is the behavior you are likely to expect).
(and it looks like you should check out the assembly released by C # , although I have never tried this)