效率问题:见e文。
For just a few items, the difference is small. If you have many items you should definitely use a switch.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
简单的说:switch在分支多的时候效率高点,其他差不多。
switch的语法说明一下:根据输入的值,决定跳到哪个case语句或default,然后再一直往下执行(除非碰到break)。
#include <stdio.h>
int main()
{
int num[6] = {3, 2, 1, 0, 2, 1};
int v0 = 0, v1 = 0, v2 = 0;
int i;
for (i = 0; i < 1; i++)
{
switch (num[i])
{
default://2
v2++;
case 2://4
v0++;
case 0://6
v1++;
case 1://
v2++;
}
}
printf("v0 = %d, v1 = %d, v2 = %d\r\n", v0, v1, v2);
getchar();
return 0;
}
如果我这样写,把default放到最前面,输入3,除了default外,下面的所有case都会执行的。(没break哟)