代码
用汇编解释前++和后++
int a = 5;
int b = ++a + 1;
std::cout << "b = " << b << std::endl;
int c = 5;
int d = c++ + 1;
std::cout << "c = " << c << std::endl;
前++
int a = 5;
01051CF8 mov dword ptr [a],5 //将5赋值给a
int b = ++a + 1;
01051CFF mov eax,dword ptr [a] //将a存储到寄存器 eax = 5
01051D02 add eax,1 //加1 eax = 5 + 1 = 6
01051D05 mov dword ptr [a],eax //寄存器赋值给a a = eax = 6
01051D08 mov ecx,dword ptr [a] //将a存储到寄存器 ecx = a = 6
01051D0B add ecx,1 //加1 ecx = ecx + 1 = 6 + 1 = 7
int b = ++a + 1;
01051D0E mov dword ptr [b],ecx //将运算结果赋值给b
std::cout << "b = " << b << std::endl; //输出结果
由汇编可以看到,++a首先进行加1处理,然后在赋值给a。
后++
int c = 5;
01051D50 mov dword ptr [c],5 //赋值给c c = 5
int d = c++ + 1;
01051D57 mov eax,dword ptr [c] //将c存储到eax eax = c = 5
01051D5A add eax,1 //eax = eax + 1 = 5 + 1 = 6
01051D5D mov dword ptr [d],eax //d = eax = 6
01051D60 mov ecx,dword ptr [c] //ecx = c = 5
01051D63 add ecx,1 //ecx = c + 1
01051D66 mov dword ptr [c],ecx //c = ecx + 1 = 5 + 1 = 6
std::cout << "c = " << c << std::endl;
由汇编可以看到,a++首先进行运算处理,将a加1后直接赋值给d,如此就将d的结果运算出来了。而后再对c进行加1的运算,最后赋值给c,完成后++运算。
|