Java 为什么我们需要在 case 语句后使用 break?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2710300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:08:13  来源:igfitidea点击:

Why do we need break after case statements?

javaswitch-statementcaselanguage-designbreak

提问by unj2

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?

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

采纳答案by WildCrustacean

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

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

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.

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

回答by Soufiane Hassou

Not having an automatic break added by the compiler makes it possible to use a switch/case to test for conditions like 1 <= a <= 3by removing the break statement from 1 and 2.

编译器没有添加自动中断使得可以使用 switch/case 来测试条件,例如1 <= a <= 3从 1 和 2 中删除 break 语句。

switch(a) {
  case 1: //I'm between 1 and 3
  case 2: //I'm between 1 and 3
  case 3: //I'm between 1 and 3
          break;
}

回答by Francisco Soto

So you do not have to repeat code if you need several cases to do the same thing:

因此,如果您需要多个案例来做同样的事情,则不必重复代码:

case THIS:
case THAT:
{
    code;
    break;
}

Or you can do things like :

或者您可以执行以下操作:

case THIS:
{
   do this;
}
case THAT:
{
   do that;
}

In a cascade fashion.

以级联方式。

Really bug/confusion prone, if you ask me.

如果你问我,真的很容易出现错误/混淆。

回答by Hellektor

Exactly, because with some clever placement you can execute blocks in cascade.

没错,因为通过一些巧妙的放置,您可以级联执行块。

回答by Zach Johnson

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

你可以用 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.

例如,假设您想对所有情况执行特定操作,但在某些情况下您希望执行该操作以及其他操作。使用带有 fall-through 的 switch 语句会很容易。

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 breakstatement at the end of a case and cause unexpected behavior. Good compilers will warn you when you omit the break statement.

当然,很容易忘记break案例末尾的语句并导致意外行为。当您省略 break 语句时,好的编译器会警告您。

回答by Jonas B

because there are situations where you want to flow through the first block for example to avoid writing the same code in multiple blocks but still be able to divide them for mroe control. There are also a ton of other reasons.

因为在某些情况下,您希望遍历第一个块,例如避免在多个块中编写相同的代码,但仍然能够将它们分开以进行 mroe 控制。还有很多其他原因。

回答by Romain Hippeau

Java comes from C and that is the syntax from C.

Java 来自 C,这是 C 的语法。

There are times where you want multiple case statements to just have one execution path. Below is a sample that will tell you how many days in a month.

有时您希望多个 case 语句只有一个执行路径。下面是一个示例,它将告诉您一个月有多少天。

class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}

回答by President James K. Polk

I think it is a mistake. As a language construct it is just as easy to have breakas the default and instead have a fallthroughkeyword. Most of the code I have written and read has a break after every case.

我认为这是一个错误。作为一种语言结构,它break与默认值一样容易,而是有一个fallthrough关键字。我编写和阅读的大多数代码在每个案例之后都有一个休息时间。

回答by Jim Lewis

Java is derived from C, whose heritage includes a technique known as Duff's Device. It's an optimization that relies on the fact that control falls through from one case to the next, in the absence of a break;statement. By the time C was standardized, there was plenty of code like that "in the wild", and it would have been counterproductive to change the language to break such constructions.

Java 源自 C,C 继承了一种称为Duff's Device的技术。这是一种优化,它依赖于这样一个事实,即在没有break;语句的情况下,控制会从一个案例转移到另一个案例。到 C 被标准化的时候,已经有很多像这样的代码“在野外”,改变语言来破坏这种结构会适得其反。

回答by Donal Fellows

Why doesn't the compiler automatically put break statements after each code block in the switch?

为什么编译器不自动在 switch 中的每个代码块之后放置 break 语句?

Leaving aside the gooddesire to be able to use the identical block for several cases (which could be special-cased)...

撇开能够在几种情况下使用相同块的良好愿望(可能是特殊情况)......

Is it for historical reasons? When would you want multiple code blocks to execute?

是历史原因吗?您希望何时执行多个代码块?

It's mainly for compatibility with C, and is arguably an ancient hack from the days of old when gotokeywords roamed the earth. It doesenable some amazing things, of course, such as Duff's Device, but whether that's a point in its favor or against is… argumentative at best.

它主要是为了与 C 兼容,可以说是古代goto关键字在地球上漫游时的古老黑客。当然,它确实实现了一些令人惊奇的事情,例如Duff's Device,但是无论这是赞成还是反对,充其量只是争论而已。