Two Tips of switch

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。