直接上代码:
1.++i
int add(int a, int b) { int c = 0; b = ++c; return a+b; } int init() { int a = add(3, 4); return a; }
对应的汇编如下:
_Z3addii: .LFB0: .cfi_startproc pushl %ebp .cfi_def_cfa_offset 8 .cfi_offset 5, -8 movl %esp, %ebp .cfi_def_cfa_register 5 subl $16, %esp movl $0, -8(%ebp) addl $1, -8(%ebp) movl -8(%ebp), %eax movl %eax, -4(%ebp) movl -4(%ebp), %eax movl 8(%ebp), %edx addl %edx, %eax leave .cfi_restore 5 .cfi_def_cfa 4, 4 ret .cfi_endproc .LFE0: .size _Z3addii, .-_Z3addii .globl _Z4initv .type _Z4initv, @function
重点分析下面这几句:
movl $0, -8(%ebp) ;这句表示 c = 0
addl $1, -8(%ebp);这句表示++c
movl -8(%ebp), %eax;这句表示将c自加的值存入临时寄存器中
movl %eax, -4(%ebp);这句表示将c自加后的值赋值给b
2.i++
int add(int a, int b) { int c = 0; b = c++; return a+b; } int init() { int a = add(3, 4); return a; }
对应的汇编如下:
_Z3addii: .LFB0: .cfi_startproc pushl %ebp .cfi_def_cfa_offset 8 .cfi_offset 5, -8 movl %esp, %ebp .cfi_def_cfa_register 5 subl $16, %esp movl $0, -8(%ebp) movl -8(%ebp), %eax movl %eax, -4(%ebp) addl $1, -8(%ebp) movl -4(%ebp), %eax movl 8(%ebp), %edx addl %edx, %eax leave .cfi_restore 5 .cfi_def_cfa 4, 4 ret .cfi_endproc .LFE0: .size _Z3addii, .-_Z3addii .globl _Z4initv .type _Z4initv, @function
重点看下面几句:
movl $0, -8(%ebp) ;这句表示c=0
movl -8(%ebp), %eax;这句表示将c的值放在临时寄存器中
movl %eax, -4(%ebp);这句表示将c未自加前的值赋值给b
addl $1, -8(%ebp);这句表示再将c的值自加1
结论:++i是先自加再使用加后的值,i++是先使用原来的值再自加。