C语言高级编程:汇编分析i++和++i

测试环境: Ubuntu 14.04

 

1. 代码

#include 


int main()
{
    int a;
    int b;
    int c;

    a = 1;
    b = a++;
    c = ++a;

    printf("b = %d, c = %d, a = %d\n", b, c, a);
}

 

2. 执行

baoli@ubuntu:~/c$ ./a.out

b = 1, c = 3, a = 3

 

 

3. 反汇编

objdump -S a.out

注:编译时加上-g

int main()
{
  40052d:    55                       push   %rbp
  40052e:    48 89 e5                 mov    %rsp,%rbp
  400531:    48 83 ec 10              sub    $0x10,%rsp
    int a;
    int b;
    int c;

    a = 1;
  400535:    c7 45 f4 01 00 00 00     movl   $0x1,-0xc(%rbp)

    b = a++;
  40053c:    8b 45 f4                 mov    -0xc(%rbp),%eax
  40053f:    8d 50 01                 lea    0x1(%rax),%edx
  400542:    89 55 f4                 mov    %edx,-0xc(%rbp)
  400545:    89 45 f8                 mov    %eax,-0x8(%rbp)

    c = ++a;
  400548:    83 45 f4 01              addl   $0x1,-0xc(%rbp)
  40054c:    8b 45 f4                 mov    -0xc(%rbp),%eax
  40054f:    89 45 fc                 mov    %eax,-0x4(%rbp)

    printf("b = %d, c = %d, a = %d\n", b, c, a);
  400552:    8b 4d f4                 mov    -0xc(%rbp),%ecx
  400555:    8b 55 fc                 mov    -0x4(%rbp),%edx
  400558:    8b 45 f8                 mov    -0x8(%rbp),%eax
  40055b:    89 c6                    mov    %eax,%esi
  40055d:    bf f4 05 40 00           mov    $0x4005f4,%edi
  400562:    b8 00 00 00 00           mov    $0x0,%eax
  400567:    e8 a4 fe ff ff           callq  400410 
}

 

4. 分析

1)b = a++

  • 先将a的值保存到eax

  • 再将rax(即eax)的值加1保存到edx

  • 将edx写回内存a,即赋值给a

  • 将eax写到内存b,及赋值给b

2)c = ++a

  • 先将a的值加1

  • 再将a的值保存到eax

  • 将eax赋值给c

3)i++和++i最终都会使i的值加1

 

 

注:

|63..32|31..16|15-8|7-0|

               |AH.|AL.|

               |AX.....|

       |EAX............|

|RAX...................|

 

 

 

 

 

你可能感兴趣的:(C语言高级编程)