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

为什么switch...case语句比if...else执行效率高

时间:2020-04-30 18:59:43      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:stat   print   switch   div   htm   data   编译器   com   nbsp   

https://www.cnblogs.com/idorax/p/6275259.html

 

switch case 语句多的时候 编译器会将switch case 转为跳转表  (.rodata)

 

 

#include <stdio.h>

static int
foo_ifelse(char c)
{
        if (c == ‘0‘ || c == ‘1‘) {
                c += 1;
        } else if (c == ‘a‘ || c == ‘b‘) {
                c += 2;
        } else if (c == ‘A‘ || c == ‘B‘) {
                c += 3;
        } else {
                c += 4;
        }

        return (c);
}

static int
foo_switch(char c)
{
        switch (c) {
                case ‘1‘:
                case ‘0‘: c += 1; break;
                case ‘b‘:
                case ‘a‘: c += 2; break;
                case ‘B‘:
                case ‘A‘: c += 3; break;
                default:  c += 4; break;
        }

        return (c);
}

int
main(int argc, char **argv)
{
        int m1 = foo_ifelse(‘0‘);
        int m2 = foo_ifelse(‘1‘);
        int n1 = foo_switch(‘a‘);
        int n2 = foo_switch(‘b‘);
        (void) printf("%c %c %c %c\n", m1, m2, n1, n2);
        return (0);
}

 

为什么switch...case语句比if...else执行效率高

标签:stat   print   switch   div   htm   data   编译器   com   nbsp   

原文地址:https://www.cnblogs.com/sinferwu/p/12810576.html

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