C++ Force compile-time error/warning on implicit fall-through in switch

前端 未结 4 2254
猫巷女王i
猫巷女王i 2020-12-23 19:40

switch statements can be super useful, but lead to a common bug where a programmer forgot a break statement:

switch(val) {
    case 0:
        f         


        
4条回答
  •  攒了一身酷
    2020-12-23 19:42

    I always write a break; before each case, as follows:

    switch(val) {
        break; case 0:
            foo();
        break; case 1:
            bar();
        break; case 2:
            baz();
        break; default:
            roomba();
    }
    

    This way, it is much more obvious to the eye if a break; is missing. The initial break; is redundant I suppose, but it helps to be consistent.

    This is a conventional switch statement, I've simply used whitespace in a different way, removing the newline that is normally after a break; and before the next case.

提交回复
热议问题