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