- 论坛徽章:
- 0
|
- 1 .file "m.c"
- 2 .section .rodata
- 3 .LC0:
- 4 .string "j is :%d,i is :%d\n"
- 5 .text
- 6 .globl main
- 7 .type main, @function
- 8 main:
- 9 pushl %ebp
- 10 movl %esp, %ebp
- 11 andl $-16, %esp
- 12 subl $32, %esp
- 13 movl $5, 28(%esp)
- 14 addl $1, 28(%esp)
- 15 subl $1, 28(%esp)
- 16 movl 28(%esp), %eax
- 17 addl %eax, %eax
- 18 subl $1, 28(%esp)
- 19 subl 28(%esp), %eax
- 20 movl %eax, 24(%esp)
- 21 movl $.LC0, %eax
- 22 movl 28(%esp), %edx
- 23 movl %edx, 8(%esp)
- 24 movl 24(%esp), %edx
- 25 movl %edx, 4(%esp)
- 26 movl %eax, (%esp)
- 27 call printf
- 28 call getchar
- 29 leave
- 30 ret
- 31 .size main, .-main
-
-
- 1 #include <stdio.h>
- 2
- 3 int main ()
- 4 {
- 5
- 6 int j,i = 5;
- 7 j = (++i)+(--i)-(--i);
- 8 printf("j is :%d,i is :%d\n",j, i);
- 9 getchar();
- 10 }
- ~
- 汇编代码分析:
- 13 movl $5, 28(%esp) ==》 i = 5; 这里的28(%esp)就是堆栈偏移28,也就是局部变量i
- 14 addl $1, 28(%esp) ==> ++i;
- 15 subl $1, 28(%esp) ==> --i;
- 到这里i的结果是5,也是符合我们预期的。
- 接下来就不是我们想看到的,
- 16 movl 28(%esp), %eax
- 17 addl %eax, %eax
- gcc编译器,把++i 和 --i的结果都放在堆栈28(%esp)同一个位置上,
- 代码17行,就相当于 5+5 ==》10, 我们预期的是11
- 然后subl $1, 28(%esp),再减1, ==》 i==4
- 那得到 j = 10 - 4, 当然结果就是6啦。
- 所以说不要在同一个点上改变一个变量两次及以上,不然会得到你不想要的结果。
- 声明:本人汇编不熟悉,临时看了下汇编语法分析的,有不对的地方,请指出。
-
-
-
-
-
- 可以参考下面的代码看:
- 下面的运行结果符合我们期望,因为 变量a、b、c 分别对应堆栈 60(%esp) 56(%esp) 52(%esp)
- 这样计算结果不会互相干扰。得到的结果就是 6+5-4 == 7
- 1 .file "mm.c"
- 2 .section .rodata
- 3 .align 4
- 4 .LC0:
- 5 .string "a is :%d,b is :%d, c is:%d, d is %d\n"
- 6 .text
- 7 .globl main
- 8 .type main, @function
- 9 main:
- 10 pushl %ebp
- 11 movl %esp, %ebp
- 12 andl $-16, %esp
- 13 subl $64, %esp
- 14 movl $5, 60(%esp)
- 15 addl $1, 60(%esp)
- 16 movl 60(%esp), %eax
- 17 movl %eax, 56(%esp)
- 18 subl $1, 60(%esp)
- 19 movl 60(%esp), %eax
- 20 movl %eax, 52(%esp)
- 21 subl $1, 60(%esp)
- 22 movl 60(%esp), %eax
- 23 movl %eax, 48(%esp)
- 24 movl 52(%esp), %eax
- 25 movl 56(%esp), %edx
- 26 leal (%edx,%eax), %eax
- 27 subl 48(%esp), %eax
- 28 movl %eax, 44(%esp)
- 29 movl $.LC0, %eax
- 30 movl 44(%esp), %edx
- 31 movl %edx, 16(%esp)
- 32 movl 48(%esp), %edx
- 33 movl %edx, 12(%esp)
- 34 movl 52(%esp), %edx
- 35 movl %edx, 8(%esp)
- 36 movl 56(%esp), %edx
- 37 movl %edx, 4(%esp)
- 38 movl %eax, (%esp)
- 39 call printf
-
-
- 1 #include <stdio.h>
- 2
- 3 int main ()
- 4 {
- 5
- 6 int j,i = 5;
- 7 int a = ++i;
- 8 int b = --i;
- 9 int c = --i;
- 10 int d = a + b - c;
- 11 printf("a is :%d,b is :%d, c is:%d, d is %d\n", a, b, c, d );
- 12 //j = (++i)+(--i)-(--i);
- 13 //printf("j is :%d,i is :%d\n",j, i);
- 14 getchar();
- 15 }
复制代码 |
|