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

前端 未结 3 1387
梦毁少年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:37

    Yes, this is allowed, and it does what you want. For a switch statement, the C++ standard says:

    case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break.

    [Note 1: Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required. Declarations can appear in the substatement of a switch statement. — end note]

    So when the if statement is evaluated, control flow proceeds according to the rules of an if statement, regardless of intervening case labels.

提交回复
热议问题