码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-18 11:08:33      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   strong   div   art   

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

 

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

标签:style   blog   http   color   io   ar   strong   div   art   

原文地址:http://www.cnblogs.com/mylinux/p/3978690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!