C语言中,条件判断语句是程序的重要组成部分,也是系统业务逻辑的控制手段,书上说switch…case…语句比if…else if…else执行效率要高,但为什么呢?
switch…case会生成一个跳转表来指示实际的case分支的地址,而这个跳转表的索引号与switch变量的值是相等的。从而,switch…case不用像if…else那样遍历条件分支直到命中条件,而只需访问对应索引号的表项从而到达定位分支的目的。
具体地说,switch…case会生成一份大小(表项数)为最大case常量+1的跳表,程序首先判断switch变量是否大于最大case 常量,若大于,则跳到default分支处理;否则取得索引号为switch变量大小的跳表项的地址(即跳表的起始地址+表项大小*索引号),程序接着跳到此地址执行,到此完成了分支的跳转。
代码:
#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);
}