因为运算符 +=、-=和*=属于同一优先级,且其结合性均为从右至左,所以atom_09描述正确。以下是VC6 + Debug方式的测试代码及其对应的汇编代码:
程序代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a = 10;
printf("%d\n", a+=a-=a*=a);
return 0;
}
输出:0
汇编代码:
8:
printf("%d\n", a+=a-=a*=a);
0040102F
mov
eax,dword ptr [ebp-4] ; dword ptr [ebp-4]就是a,执行后,eax = 10
00401032
imul
eax,dword ptr [ebp-4] ; 10 * 10 = 100
00401036
mov
dword ptr [ebp-4],eax ; 把乘积的结果又写回a,导致a = 100
00401039
mov
ecx,dword ptr [ebp-4] ; 又把100给ecx
0040103C
sub
ecx,dword ptr [ebp-4] ; 100 - a = 100 - 100 = 0
0040103F
mov
dword ptr [ebp-4],ecx ; 把0写回a
00401042
mov
edx,dword ptr [ebp-4] ; 把a的值又取出来给寄存器edx,结果edx = 0
00401045
add
edx,dword ptr [ebp-4] ; 0 + a = 0 + 0 = 0
00401048
mov
dword ptr [ebp-4],edx ; 把0又写回a
0040104B
mov
eax,dword ptr [ebp-4] ; eax = a = 0
0040104E
push
eax
; 入栈准备打印eax
0040104F
push
offset string "%d\n" (0042201c)
00401054
call
printf (00401090)
00401059
add
esp,8
9:
10:
return 0;