views:

610

answers:

13

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?

+1  A: 

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

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;
}
Soufiane Hassou
+15  A: 

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.

bde
Just always add a comment along the lines `// Intentional fallthrough.` when you omit a break. It's not so much a bad style as "easy to forget a break accidentally" in my opinion. P.S. Of course not in simple cases as in the answer itself.
doublep
@doublep - I agree. In my opinion, I'd avoid it if possible but if it makes sense then make sure it is very clear what you are doing.
bde
@doublep: I'd not bother with the comment if the multiple `case` s are stacked together that way. If there's code in between them then yes, the comment is probably merited.
Billy ONeal
+2  A: 

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.

Francisco Soto
A: 

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

+5  A: 

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.

Zach Johnson
Can switch/case be used on strings in Java?
Steve Kuo
@Steve: Oops, I guess not at the moment. According to http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java/338230#338230, strings will be allowed in a future version of Java. (I currently do most of my programming in C#, which does allow strings in switch statements.) I've edited the answer to remove the misleading quotes.
Zach Johnson
A: 

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.

Jonas B
+4  A: 

Java comes from C and that is the syntax from 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.

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);
    }
}
Romain Hippeau
Why did I get dinged ?
Romain Hippeau
Someone aimed for the up arrow and missed? Or maybe they had a beef with your brace style or indentation...
Jim Lewis
Dunno, so have a +1 from me. This is an example where the fall-through helps, though I really wish Java had picked a more modern case statement. Cobol's EVALUATE-WHEN-OTHERWISE is far more powerful, and *predates* Java. Scala's match expression is a modern example of what could be done.
Jim Ferrans
+3  A: 

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

GregS
I'd rather suggest `continue <case name>` which allows to explicitly specify with which case statement to continue;
Vilx-
+1  A: 

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.

Jim Lewis
A: 

All these answers are correct. I've always found switches useful when building algorithms for say games and stuff

a = 1; 

switch(a){
   case 1:
      turnLeft();
   case 2:
      walkForward()
}
Glycerine
+3  A: 

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

Leaving aside the good desire 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 goto keywords roamed the earth. It does enable 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.

Donal Fellows
+8  A: 

Historically, it's because the case was essentially defining a label, also known as the target point of a goto call. The switch statement and its associated cases really just represent a multiway branch with multiple potential entry points into a stream of code.

All that said, it has been noted a nearly infinite number of times that break is almost always the default behavior that you'd rather have at the end of every case.

Bob Cross
A: 

As far as the historical record goes, Tony Hoare invented the case statement in the 1960s, during the "structured programming" revolution. Tony's case statement supported multiple labels per case and automatic exit with no stinking break statements. The requirement for an explicit break was something that came out of the BCPL/B/C line. Dennis Ritchie writes (in ACM HOPL-II):

For example, the endcase that escapes from a BCPL switchon statement was not present in the language when we learned it in the 1960s, and so the overloading of the break keyword to escape from the B and C switch statement owes to divergent evolution rather than conscious change.

I haven't been able to find any historical writings about BCPL, but Ritchie's comment suggests that the break was more or less a historical accident. BCPL later fixed the problem, but perhaps Ritchie and Thompson were too busy inventing Unix to be bothered with such a detail :-)

Norman Ramsey