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

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);
}

 

posted @ 2020-04-30 18:19  sinferwu  阅读(461)  评论(0编辑  收藏  举报