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

参考: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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值