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

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

    As other answers have mentioned, this is technically allowed by the standard, but it is very confusing and unclear to future readers of the code.

    This is why switch ... case statements should usually be written with function calls and not lots of inline code.

    switch(i) {
    case 0:
        do_zero_case(); do_general_stuff(); break;
    case 1:
        do_one_case(); do_general_stuff(); break;
    case 2:
        do_general_stuff(); break;
    default:
        do_default_not_zero_not_one_not_general_stuff(); break;
    }
    

提交回复
热议问题