C语言编程中,什么时候用一条switch语句比用多条if语句更好
如果你有两个以上基于同一个数字(numeric)型变量的条件表达式,那么最好使用一条switch语句。
例如,与其使用下述代码:
if (x ==l)
printf ("x is equal to one. \n");
else if (x ==2)
printf ("x is equal to two. \n");
else if (x = =3)
printf ("x is equal to three. \n");
else
printf ("x is not equal to one, two, or three. \n");
不如使用下述代码,它更易于阅读和维护:
switch (x)
{
case 1: printf ("x is equal to one. \n");
break;
case 2: printf ("x is equal to two. \n");
break
case 3: printf ('x is equal to three. \n");
break;
default: printf ("x is not equal to one, two, or three. \n");
break;
}
注意:使用switch语句的前提是条件表达式必须基于同一个数字型变量。例如,尽管下述if语句包含两个以上的条件,但该例不能使用switch语句,因为该例基于字符串比较,而不是数字比较:
char *name="Lupto";
if(!stricmp(name,"Isaac"))
printf("Your name means'Laughter'.\n");
else if(!stricmp(name,"Amy"))
printf("Your name means'Beloved'.\n");
else if(!stricmp(name,"Lloyd"))
printf("Your name means'Mysterious'.\n");
else
printf("I haven't a clue as to what your name means.\n");
请参见:
1、switch语句必须包含default分支吗7
2、switch语句的最后一个分支可以不要break语句吗?
例如,与其使用下述代码:
if (x ==l)
printf ("x is equal to one. \n");
else if (x ==2)
printf ("x is equal to two. \n");
else if (x = =3)
printf ("x is equal to three. \n");
else
printf ("x is not equal to one, two, or three. \n");
不如使用下述代码,它更易于阅读和维护:
switch (x)
{
case 1: printf ("x is equal to one. \n");
break;
case 2: printf ("x is equal to two. \n");
break
case 3: printf ('x is equal to three. \n");
break;
default: printf ("x is not equal to one, two, or three. \n");
break;
}
注意:使用switch语句的前提是条件表达式必须基于同一个数字型变量。例如,尽管下述if语句包含两个以上的条件,但该例不能使用switch语句,因为该例基于字符串比较,而不是数字比较:
char *name="Lupto";
if(!stricmp(name,"Isaac"))
printf("Your name means'Laughter'.\n");
else if(!stricmp(name,"Amy"))
printf("Your name means'Beloved'.\n");
else if(!stricmp(name,"Lloyd"))
printf("Your name means'Mysterious'.\n");
else
printf("I haven't a clue as to what your name means.\n");
请参见:
1、switch语句必须包含default分支吗7
2、switch语句的最后一个分支可以不要break语句吗?