为什么我们在 case 语句之后需要 break?

为什么编译器不自动在 switch 中的每个代码块之后放置 break 语句?是因为历史原因吗?您希望何时执行多个代码块?

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 execute?

推荐答案

有时将多个案例关联到同一个代码块会很有帮助,例如

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;

等等.只是一个例子.

根据我的经验,失败"并为一个案例执行多个代码块通常是不好的风格,但在某些情况下可能会有用处.

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.

相关文章