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

前端 未结 4 2253
猫巷女王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:59

    Here's an answer to compulsively hate.

    First, switch statements are fancy gotos. They can be combined with other control flow (famously, Duff's Device), but the obvious analogy here is a goto or two. Here's a useless example:

    switch (var) {
        CASE1: case 1:
            if (foo) goto END; //same as break
            goto CASE2; //same as fallthrough
        CASE2: case 2:
            break;
        CASE3: case 3:
            goto CASE2; //fall *up*
        CASE4: case 4:
            return; //no break, but also no fallthrough!
        DEFAULT: default:
            continue; //similar, if you're in a loop
    }
    END:
    

    Do I recommend this? No. In fact, if you're considering this just to annotate a fall-through, then your problem is actually something else.

    This sort of code does make it very clear that a fall-through can happen in case 1, but as the other bits show, this is a very powerful technique in general that also lends itself to abuse. Be careful if you use it.

    Forgetting a break? Well, then you'll also occasionally forget whatever annotation you pick. Forgetting to account for fall-through when changing a switch statement? You're a bad programmer. When modifying switch statements(or really any code), you need to first understand them.


    Honestly, I very seldom make this kind of error (forgetting a break)--certainly less than I made other "common" programming errors (strict aliasing, for example). To be safe, I currently do (and recommend you to do) just write //fallthrough, since this at least clarifies intention.

    Other than that, it's a just a reality that programmers need to accept. Proofread your code after you write it and find the occasional problem with debugging. That's life.

提交回复
热议问题