Why do we need break after case statements?

后端 未结 17 2232
猫巷女王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 05:01

    Sometimes it is helpful to have multiple cases associated with the same code block, such as

    case 'A':
    case 'B':
    case 'C':
        doSomething();
        break;
    
    case 'D':
    case 'E':
        doSomethingElse();
        break;
    

    etc. Just an example.

    In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.

提交回复
热议问题