利用 操作符特性 代替if判断语句

参考: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");
}
上一篇:Web Scraper 翻页——控制链接批量抓取数据


下一篇:【CSS3动画】transform对文字及图片的旋转、缩放、倾斜和移动