参考:http://blog.csdn.net/speedme/article/details/22916181
1.&&的判断特性
#include <stdio.h> int sumf(int i) { int sum = 0; #if 0 i && (sum = i+ sumf(i-1)); #else if(i!=0){ sum = i+ sumf(i-1); } #endif return sum; } int main() { printf("sum(%d)=%d\n",4,sumf(4)); printf("aaaaaaaaaaaa\n"); }
用gcc编译,看起来if判断语句效率还高一点。
sumf:// if(i!=0){ sum = i+ sumf(i-1); } pushl %ebp movl %esp, %ebp subl $40, %esp movl $0, -12(%ebp) cmpl $0, 8(%ebp) je .L2 movl 8(%ebp), %eax subl $1, %eax movl %eax, (%esp) call sumf addl 8(%ebp), %eax movl %eax, -12(%ebp) .L2: movl -12(%ebp), %eax leave ret
sumf://i && (sum = i+ sumf(i-1));
pushl %ebp movl %esp, %ebp subl $40, %esp movl $0, -12(%ebp) cmpl $0, 8(%ebp) je .L3 movl 8(%ebp), %eax subl $1, %eax movl %eax, (%esp) call sumf addl 8(%ebp), %eax movl %eax, -12(%ebp) cmpl $0, -12(%ebp) .L3: movl -12(%ebp), %eax leave ret
2.另类的迭代法:::::(!的判断特性这个比较实用一点)
#include <stdio.h> typedef unsigned int (*fun)(unsigned int); unsigned int Solution3_Teminator(unsigned int n) { return 0; } unsigned int Sum_Solution3(unsigned int n) { static fun f[2] = {Solution3_Teminator, Sum_Solution3}; return n + f[!!n](n - 1); //注意此处 } int sumf(int i) { int sum = 0; #if 0 i && (sum = i+ sumf(i-1)); #else if(i!=0){ sum = i+ sumf(i-1); } #endif return sum; } int main() { printf("Sum_Solution3(%d)=%d\n",4,Sum_Solution3(4)); printf("sum(%d)=%d\n",4,sumf(4)); printf("aaaaaaaaaaaa\n"); }
时间: 2024-10-01 04:42:41