0x01 switch语句的执行流
switch语句在没有break;
语句的情况下,逐一执行每个case
子句。
示例代码如下:
#include<stdio.h>
void main(void)
{
char ch;
int chars=0,words=0,lines=0;
while( (ch=getchar())!=EOF )
{
switch(ch)
{
case '\n':
lines+=1;
case '\t':
case ' ':
words+=1;
default:
chars+=1;
}
}
printf("Character:%d\nWord:%d\nLine:%d\n",chars,words,lines);
}
输入内容及运行结果如图:
image
上述代码并未考虑过于复杂的情形。
如果在第一个case
子句中间加入break;
:
#include<stdio.h>
void main(void)
{
char ch;
int chars=0,words=0,lines=0;
while( (ch=getchar())!=EOF )
{
switch(ch)
{
case '\n':
lines+=1;
break;
case '\t':
case ' ':
words+=1;
default:
chars+=1;
}
}
printf("Character:%d\nWord:%d\nLine:%d\n",chars,words,lines);
}
结果会变成:
image
可以看出:Character数量变为26(少了两个换行符);Word数量变为3(少了ERFZE、everyone)。这是因为执行流在执行到第一个case
子句中遇到break;
,不再继续向下执行。
0x02 switch语句中出现continue;
如果switch的语句中出现continue;
,gcc
在编译时会报错:
image
continue;
并未用于循环,即switch语句中不能出现continue;
。
如果switch位于循环语句的代码块中,那么continue;
语句将会生效,作用同正常使用时一样:
#include<stdio.h>
void main(void)
{
char ch;
int count=-1;
while( count<3 )
{
count+=1;
switch(count)
{
case 0:
continue;
default:
printf("%d:Hahah\n",count);
}
}
}
运行结果:
image