首先,上代码:
#include <stdio.h> #include <iostream> using namespace std; int main() { int a = 5; printf("a++ = %d\n", a++); a = 5; printf("++a = %d\n", ++a); a = 5; printf("a += a++ =%d\n", a += a++); a = 5; printf("a += (a++) =%d\n", a = a + (a++)); a = 5; printf("a += ++a =%d\n", a += ++a); a = 5; printf("a += (++a) =%d\n", a += (++a)); a = 5; printf("++a += a++ =%d\n", ++a += a++); a = 5; printf("(++a) += (a++) =%d\n", (++a) += (a++)); return 1; }
不知道各位看官看到这儿有什么想法,你认为它们的输出值应该是什么?
不卖关子了,直接给出VS2013下的运行结果和g++ 4.8.2编译出的运行结果:
如此截然不同的结果,那么我们看一下汇编代码(只截取了【printf("a += a++ =%d\n", a += a++);】部分的汇编作为示例,具体的大家可以自己看一下):
/* vs2013 */ 13: printf("a += a++ =%d\n", a += a++); 011ECAC7 mov eax,dword ptr [a] 011ECACA add eax,dword ptr [a] 011ECACD mov dword ptr [a],eax 011ECAD0 mov ecx,dword ptr [a] 011ECAD3 mov dword ptr [ebp-0D0h],ecx 011ECAD9 mov edx,dword ptr [a] 011ECADC add edx,1 011ECADF mov dword ptr [a],edx 011ECAE2 mov esi,esp 011ECAE4 mov eax,dword ptr [ebp-0D0h] 011ECAEA push eax 011ECAEB push 11F832Ch 011ECAF0 call dword ptr ds:[11FC1E4h] 011ECAF6 add esp,8 011ECAF9 cmp esi,esp 011ECAFB call __RTC_CheckEsp (011E1631h)
/* g++ 4.8.2 */ 13 printf("a += a++ =%d\n", a += a++); 0x08048602 <+85>: mov 0x1c(%esp),%eax 0x08048606 <+89>: lea 0x1(%eax),%edx 0x08048609 <+92>: mov %edx,0x1c(%esp) 0x0804860d <+96>: add %eax,0x1c(%esp) 0x08048611 <+100>: mov 0x1c(%esp),%eax 0x08048615 <+104>: mov %eax,0x4(%esp) 0x08048619 <+108>: movl $0x8048814,(%esp) 0x08048620 <+115>: call 0x80484a0 <[email protected]>
我书读得少,汇编更是自学成才,希望大家能帮忙解释一下是神马情况~~~,小弟多谢了!
【注】上述代码运行平台均为32位操作系统,其中vs2013运行于Windows 8.1 企业版,g++运行于ubuntu14.04 (3.13.0-41-generic)
时间: 2024-10-18 04:29:50