Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Who decided, and basing on what concepts, that switch construction (in many languages) has to be, like it is? Why do we have to use break in each statement? Why do we have to write something like this:

switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}

I've noticed this construction in PHP and JS, but there are probably many other languages that uses it.

If switch is an alternative of if, why we can't use the same construction for switch, as for if? I.e.:

switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}

It is said, that break prevents execution of a blocks following current one. But, does someone really run into situation, where there was any need for execution of current block and following ones? I didn't. For me, break is always there. In every block. In every code.

share|improve this question
1  
As most of the answers have noted, this is related to 'fall-through', where multiple conditions are routed through the same 'then' blocks. However, this is language dependent - RPG, for example, treats a CASE statement equivalently to a giant if/elseif block. –  Clockwork-Muse Aug 28 '12 at 15:51
17  
It was a poor decision made by the C-designers (like many decisions, it was made to make the transition from assembly --> C, and the translation back, easier, rather than for ease of programming), which was then unfortunately inherited in other C-based languages. Using the simple rule "Always make the common case the default!!", we can see that the default behaviour should have been to break, with a separate keyword for falling through, since that is by far the most common case. –  BlueRaja - Danny Pflughoeft Aug 28 '12 at 16:25
2  
I have used fall-through on several occasions, though arguably the switch statement in my preferred language at the time (C) could have been designed to avoid it; e.g. I have done case 'a': case 'A': case 'b': case 'B' but mostly because I cannot do case in [ 'a', 'A', 'b', 'B' ]. A slightly better question is, in my current preferred language (C#), the break is mandatory, and there is no implicit fall-though; forgetting break is a syntax error... :\ –  Michael Edenfield Aug 28 '12 at 18:20
1  
Fall-through with actual code is often found in parser implementations. case TOKEN_A: /*set flag*/; case TOKEN_B: /*consume token*/; break; case TOKEN_C: /*...*/ –  OrangeDog Aug 28 '12 at 19:25
    
@MichaelEdenfield - ugh, this is one of my c# pet peeves too. If you're going to enforce it in order to "protect me", at least provide a way to do the fall through when I choose to (eg. allow a continue statement in place of break to explicitly fall through). –  Alconja Aug 29 '12 at 0:14
show 7 more comments

10 Answers

up vote 64 down vote accepted

C was one of the first languages to have the switch statement in this form, and all other major languages inherited it from there, mostly choosing to keep the C semantics per default - they either didn't think of the advantages of changing it, or judged them less important than keeping the behaviour everyone was used to.

As for why C was designed that way, it probably stems from the concept of C as "portable assembly". The switch statement is basically an abstraction of a branch table, and a branch table also has an implicit fall-through and requires an additional jump instruction to avoid it.

So basically, the designers of C also chose to keep the assembler semantics per default.

share|improve this answer
2  
VB.NET is example of an language that did change it. There is no danger of the having it flow into the case clause. –  poke Aug 28 '12 at 13:30
1  
Tcl's another language that doesn't ever fall through to the next clause. Virtually never wanted to do it either (unlike in C where it's useful when writing certain types of programs). –  Donal Fellows Aug 28 '12 at 19:01
3  
C's ancestor languages, B and the older BCPL, both have (had?) switch statements; BCPL spelled it switchon. –  Keith Thompson Aug 28 '12 at 22:13
    
Ruby's case statements don't fall through; you can get similar behavior by having two test values in a single when. –  Nathan Long Aug 29 '12 at 12:52
add comment

Because switch is not an alternative of if ... else statements in those languages.

By using switch, we can match more than one condition at a time, which is highly appreciated in some cases.

Example:

public Season SeasonFromMonth(Month month)
{
    Season season;
    switch (month)
    {
        case Month.December:
        case Month.January:
        case Month.February:
            season = Season.Winter;
            break;

        case Month.March:
        case Month.April:
        case Month.May:
            season = Season.Spring;
            break;

        case Month.June:
        case Month.July:
        case Month.August:
            season = Season.Summer;
            break;

        default:
            season = Season.Autumn;
            break;
    }

    return season;
}
share|improve this answer
11  
more than one block ... unwanted in most cases I am not agree with you. –  Satish Pandey Aug 28 '12 at 9:36
2  
@DanielB It depends on the language though; C# switch statements don't allow for that possiblity. –  Andy Aug 28 '12 at 11:55
4  
@Andy Are we talking about fall-through still? C# switch statements definitely allow for it (check the 3rd example), hence the need for break. But yes, as far as I'm aware, Duff's Device does not work in C#. –  Daniel B Aug 28 '12 at 12:02
7  
@DanielB Yes we are, but the compiler won't allow a condition, code, and then another condition without a break. You can have mutliple conditions stacked with no code between, or you need a break. From your link C# does not support an implicit fall through from one case label to another. You can do fall through, but there's no chance of accidently forgetting a break. –  Andy Aug 28 '12 at 12:10
3  
@Matsemann .. I now we can do all the stuff using if..else but in some situations switch..case would be preferable. The above example would be bit complex if we use if-else. –  Satish Pandey Aug 28 '12 at 14:54
show 9 more comments

This has been asked on stackoverflow (although in C context): http://stackoverflow.com/questions/252489/why-was-the-switch-statement-designed-to-need-a-break

To summarize the accepted answer, it was probably a mistake. Most other languages have probably just followed C. However, e.g. C# seems to have fixed this by allowing fall-through but only when the programmer explicitly tells so (source: the link above, I don't speak C# myself).

share|improve this answer
    
Google Go does the same thing IIRC (allowing fallthrough if explicitly specified). –  Leo Aug 28 '12 at 11:56
    
PHP does, also. And the more you look at the resulting code, the uneasier it makes you feel. I like the /* FALLTHRU */ comment in the answer linked by @Tapio above, to prove you meant it. –  DaveP Aug 28 '12 at 13:29
1  
Saying C# has goto case, as the link does, doesn't illustrate why that works so well. You can still stack multiple cases like above, but as soon as you insert code, you have to have an explicit goto case whatever to fall through to the next case or you get a compiler eror. If you ask me, of the two, the ability to stack cases without worrying about inadvertent fall-through through negligence is by far a better feature than enabling explicit fall-through with goto case. –  Jesper Aug 28 '12 at 14:48
add comment

I will answer with an example. If you wanted to list the number of days for each month of a year, it is obvious that some months have 31, some 30, and 1 28/29. It would look like this,

switch(month) {
    case 4:
    case 6:
    case 9:
    case 11;
        days = 30;
        break;
    case 2:
        //Find out if is leap year( divisible by 4 and all that other stuff)
        days = 28 or 29;
        break;
    default:
        days = 31;
}

This is an example where multiple cases have the same effect and are all grouped together. There was obviously a reason for the choice of the break keyword and not the if ... else if construct.

The main thing to take note here is that a switch statement with many similar cases is not an if ... else if ... else if ... else for each of the cases, but rather if(1, 2, 3) ... else if(4,5,6) else ...

share|improve this answer
1  
Your example looks more verbose than an if without any benefit. Perhaps if your example assigned a name or did month-specific work in addition to the fall-through, the utility of fall-through would be more apparent? (without commenting on whether one SHOULD in the first place) –  horatio Aug 28 '12 at 18:26
1  
That is true. I was however just attempting to show cases where fall through could be used. It would obviously be much better if each of the months needed something done individually. –  Awemo Aug 29 '12 at 9:21
add comment

There are two situations where "fall through" from one case to another can happen - the empty case:

switch ( ... )
{
  case 1:
  case 2:
    do_something_for_1_and_2();
    break;
  ...
}

and the non-empty case

switch ( ... )
{
  case 1:
    do_something_for_1();
    /* Deliberately fall through */
  case 2:
    do_something_for_1_and_2();
    break;
...
}

Notwithstanding the reference to Duff's Device, legitimate instances for second are few-and-far between, and generally prohibited by coding standards and flagged during static analysis. And where it is found, is more often than not due to the omission of the break

The former is perfectly sensible and common.

To be honest, I can see no reason for needing the break and the language parser knowing that an empty case-body is a fall through, while a non-empty case is standalone.

It is a pity that the ISO C panel seem more preoccupied with adding new (unwanted) and badly defined features to the language, rather than fixing the undefined, unspecified or implementation-defined features, not to mention the illogical.

share|improve this answer
add comment

Break statement is a jumping statement that allows the user to exit the nearest enclosing switch (for your case), while, do, for or foreach. it's just as easy as that.

share|improve this answer
add comment

Not forcing the break allows a number of things that could otherwise be difficult to do. Others have noted grouping cases, for which there are a number of non-trivial cases.

One case where it is imperative that the break not be used is Duffs Device. This is used to unroll loops where it can speed up operations by limiting the number of comparisons required. I believe the initial use allowed functionality which had previously been too slow with a fully rolled up loop. It trades of code size for speed in some cases.

It is good practice to replace the break with an appropriate comment if the case has any code. Otherwise, someone will fix the missing break, and introduce a bug.

share|improve this answer
add comment

In C, where the origin seems to be, the code block of the switch statement is not a special construct. It is a normal block of code, just as a block under an if statement.

switch ()
{
}

if ()
{
}

case and default are jump labels inside this block, specifically related to switch. They are handled just as normal jump labels for goto. There is one specific rule that is important here: Jump labels can be nearly everywhere in the code, without interrupting the code flow.

As a normal code block, it doesn't need to be a compound statement. The labels are optional, too. These are valid switch statements in C:

switch (a)
    case 1: Foo();

switch (a)
    Foo();

switch (a)
{
    Foo();
}

The C standard itself gives this as an example (6.8.4.2):

switch (expr) 
{ 
    int i = 4; 
    f(i); 
  case 0: 
    i=17; 
    /*falls through into default code */ 
  default: 
    printf("%d\n", i); 
} 

In the artificial program fragment, the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

Furthermore, default is a jump label, too, and thus can be anywhere, without the need to be the last case.

This also explains Duff's Device:

switch (count % 8) {
    case 0: do {  *to = *from++;
    case 7:       *to = *from++;
    case 6:       *to = *from++;
    case 5:       *to = *from++;
    case 4:       *to = *from++;
    case 3:       *to = *from++;
    case 2:       *to = *from++;
    case 1:       *to = *from++;
            } while(--n > 0);
}

Why the fall-through? Because in the normal code flow in a normal block of code, fall-through to the next statement is expected, just as you would expect it in an if code block.

if (a == b)
{
    Foo();
    /* "Fall-through" to Bar expected here. */
    Bar();
}

switch (a)
{
    case 1: 
        Foo();
        /* Automatic break would violate expected code execution semantics. */
    case 2:
        Bar();
}

My guess is that the reason for this was ease of implementation. You don't need special code for parsing and compiling a switch block, caring for special rules. You just parse it like any other code and only have to care for the labels and the jump selection.

An interesting follow-up question from all this is if the following nested statements print "Done." or not.

int a = 10;

switch (a)
{
    switch (a)
    {
        case 10: printf("Done.\n");
    }
}

The C standard cares for this (6.8.4.2.4):

A case or default label is accessible only within the closest enclosing switch statement.

share|improve this answer
add comment

Who said you have to use a break? This works fine in c#:

public static string GetString(int id)
{
    switch (id)
    {
        case 1:
            return "one";
        case 2:
            return "two";
        case 3:
            return "three";
        default:
            return "nothing";
    }
}

In certain contexts, it isn't required.

share|improve this answer
    
My question was about global idea, not certain context. I thing there are much more situation, where you want to do something with variable set inside switch, so your context of returining program flow immediatelly from switch isn't good idea in that case. –  trejder Aug 30 '12 at 8:34
    
Actually, you were asking questions all over the place in your original post, some was about global concepts, some was not. I think you just don't like the fact that I countered your assumption that was in your title "Why do we have to use break in switch". Don't expect me to answer your plethora of questions all in one answer when other answers haven't either. –  ROFLwTIME Sep 5 '12 at 12:49
add comment

I think that with all written above - the main outcome of this thread is that if you are to design a new language - the default should be that you do not need to add a break statement and the compiler will treat it as if you did.

If you want that rare case where you want to continue on to the next case - simply state it with a continue statement.

This can be improved so that only if you use curly brackets inside the case then it doesn't go on so that the example with the months above of several cases performing the same exact code - would always work as expected without needing the continue.

share|improve this answer
    
I am not sure I understand your suggestion relative to the continue statement. Continue has a very different meaning in C and C++ and if a new language was like C, but used the keyword sometimes as with C and sometimes in this alternative way, I think confusion would reign. While there may be some issues with falling from one labelled block into another, I like the use of multiple cases with the same handling with a shared block of code. –  DeveloperDon Oct 5 '12 at 1:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.