Is using if (0) to skip a case in a switch supposed to work?

前端 未结 3 1389
梦毁少年i
梦毁少年i 2020-12-23 19:52

I have a situation where I would like for two cases in a C++ switch statement to both fall through to a third case. Specifically, the second case would fall through to the t

3条回答
  •  清歌不尽
    2020-12-23 20:43

    Yes, this is supposed to work. The case labels for a switch statement in C are almost exactly like goto labels (with some caveats about how they work with nested switch statements). In particular, they do not themselves define blocks for the statements you think of as being "inside the case", and you can use them to jump into the middle of a block just like you could with a goto. When jumping into the middle of a block, the same caveats as with goto apply regarding jumping over initialization of variables, etc.

    With that said, in practice it's probably clearer to write this with a goto statement, as in:

        switch (i) {
        case 0:
            putchar('a');
            goto case2;
        case 1:
            putchar('b');
            // @fallthrough@
        case2:
        case 2:
            putchar('c');
            break;
        }
    

提交回复
热议问题