作为"&&"和"||"操作符的操作数表达式,这些表达式在进行求值时,只要最终的结果已经可以确定是真或假,求值过程便告终止,这称之为短路求值(short-circuit evaluation)。这是这两个操作符的一个重要属性。
C++源代码:
#include<stdio.h> int Accumulation(int number) { number&&(number+=Accumulation(number-1)); return number; } int main() { int res=Accumulation(5); printf("%d\n",res); }生成的汇编代码:
int Accumulation(int number) { 003A1660 push ebp 003A1661 mov ebp,esp 003A1663 sub esp,0C0h 003A1669 push ebx 003A166A push esi 003A166B push edi 003A166C lea edi,[ebp-0C0h] 003A1672 mov ecx,30h 003A1677 mov eax,0CCCCCCCCh 003A167C rep stos dword ptr es:[edi] number && (number += Accumulation(number - 1)); 003A167E cmp dword ptr [number],0 把number值和0比较 003A1682 je Accumulation+39h (03A1699h) 相等则跳出循环 003A1684 mov eax,dword ptr [number] 003A1687 sub eax,1 减1 003A168A push eax 压入栈作为参数 003A168B call Accumulation (03A1339h) 继续调用自己形成递归 003A1690 add esp,4 003A1693 add eax,dword ptr [number] 003A1696 mov dword ptr [number],eax return number; 003A1699 mov eax,dword ptr [number] }C++源代码:
#include<stdio.h> int Accumulation(int number) { (number==0)||(number+=Accumulation(number-1)); return number; } int main() { int res=Accumulation(5); printf("%d\n",res); }生成的汇编代码:
int Accumulation(int number) { 00201660 push ebp 00201661 mov ebp,esp 00201663 sub esp,0C0h 00201669 push ebx 0020166A push esi 0020166B push edi 0020166C lea edi,[ebp-0C0h] 00201672 mov ecx,30h 00201677 mov eax,0CCCCCCCCh 0020167C rep stos dword ptr es:[edi] (number == 0) || (number += Accumulation(number - 1)); 0020167E cmp dword ptr [number],0 00201682 je Accumulation+39h (0201699h) 00201684 mov eax,dword ptr [number] 00201687 sub eax,1 0020168A push eax 0020168B call Accumulation (0201339h) 00201690 add esp,4 00201693 add eax,dword ptr [number] 00201696 mov dword ptr [number],eax return number; 00201699 mov eax,dword ptr [number] }||的情况和&&基本一样,就不再赘述了。