Why do we need break after case statements?

后端 未结 17 2030
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

17条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:40

    You can do all sorts of interesting things with case fall-through.

    For example, lets say you want to do a particular action for all cases, but in a certain case you want to do that action plus something else. Using a switch statement with fall-through would make it quite easy.

    switch (someValue)
    {
        case extendedActionValue:
            // do extended action here, falls through to normal action
        case normalActionValue:
        case otherNormalActionValue:
            // do normal action here
            break;
    }
    

    Of course, it is easy to forget the break statement at the end of a case and cause unexpected behavior. Good compilers will warn you when you omit the break statement.

提交回复
热议问题