美文网首页
C switch执行流程

C switch执行流程

作者: SnC_ | 来源:发表于2020-12-29 17:11 被阅读0次

    试想一下以下C代码会输出什么结果?

    #include <stdlib.h>
    #include <stdio.h>
    int main()
    {
        int a = 1;
        switch(a) {
            case 1:
            case 2:
            case 3:
                printf("is this case3?\n");
            case 4: case 5:
                printf("is this case5?\n");
                break;
            default:
                printf("this is default\n");
                break;
        }
        return 0;
    }
    

    switch statement大多数情况下的使用场景为

    switch(var)
        case value1:
          <code block1>
          break;
        case value2:
          <code block2>
          break;
        ... ...
    

    久而久之会形成一个思维习惯:只有case对上的那一段clode block会被执行。
    实际上,即使一个case对上了,但在遇到break之前,switch的flow of control会继续往下,并且之后的code block都会被认为满足条件,并被执行。
    开头的那段代码,最后的输出为:

    is this case3?
    is this case5?
    

    当使用case1、2、3,以及case4和5这种并列的条件时,并不会严格地在每个case后加上break,所以这是一个我认为在编程中可能会引起bug的点。

    相关文章

      网友评论

          本文标题:C switch执行流程

          本文链接:https://www.haomeiwen.com/subject/mnfqoktx.html