在通过C Primer Plus 第6版进行C语言学习的时候,我发现书中对switch语句的描述不太清晰,看后仍有疑问。经过搜索及查找资料,下面列出一些我觉得需要补充的、有关switch语句的知识点。有可能有些许错误,还请各位甄别。
1、C Primer Plus 第6版(英文版P283,中文版P205)中对switch语句结构的描述:
switch (integer expression) //switch (整型表达式)
{
case constant1: //常量1
statements <--optional //语句 <--可选
case constant2: //常量2
statements <--optional //语句 <--可选
default: <-- optional
statements <-- optional
}
英文资料中对switch语句结构的描述:(参考1)(参考2)
switch(expression) { //表达式
case constant-expression : //常量表达式
statement(s); //语句(s)
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */ //可以有任意个case语句
default : /* Optional */
statement(s);
}
中文资料:
switch语句的一般形式为:
switch(表达式)
{
case (常量表达式1) : 语句集合1;
......
case (常量表达式n) : 语句集合n;
default:执行语句集合(n+1);
}
故推测switch语句中的每个case内均可写由一个多行语句构成的复合代码(即可以写语句块)。而C Primer Plus未提及。
2、两个case的标签(label)值不可以相同,否则程序会出现编译错误。
3、case的标签必须为常量表达式(表达式内只有常量值),原书亦提及不可使用变量作标签。
错误示范:
#include <stdio.h>
int main(void)
{
int arg[3] = {1,2,3};
switch(xxx) {
case arg[0] :
printf("666\n"); //错误
break;
}
return 0;
}
4、case标签的数量,一般不做限制。直到内存用尽前,一般都可以再增加case标签。ANSI C标准规定一个switch语句内至少可以提供257个case标签。
5、default的位置不一定要在所有的case后,在switch语句的语句体内的任意位置即可。不影响程序运行。当程序寻找完所有的case标签但仍未找到符合的case时,会自动转到default。
6、编译器不会编译运行switch语句体内、第一个case之前的语句(即这些语句将不会有效)。
示例:
#include <stdio.h>
int main(void)
{
char ch;
scanf("%c",& ch);
switch (ch)
{
int i; //此语句无效
int j; //此语句无效
case 'a' :
xxx;
break;
}
return 0;
}
7、switch语句内的case语句不需要写花括号。写花括号并没有语法错误,也不会影响程序运行速度,但是这种编程习惯应尽量淘汰。(参考)