为什么我们需要在 case 语句后使用 break? [英] Why do we need break after case statements?

查看:37
本文介绍了为什么我们需要在 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?

推荐答案

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

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.

这篇关于为什么我们需要在 case 语句后使用 break?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆