177

For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.

Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?

Edit: I wasn't specific enough to what I meant by fall-through. I use this type a lot:

    switch(m_loadAnimSubCt){
        case 0:
        case 1:
            // Do something
            break;
        case 2:
        case 3:
        case 4:
            // Do something
            break;
   }

However, I'm concerned about something like this.

   switch(m_loadAnimSubCt){
        case 0:
        case 1:
            // Do something, but fall through to the other cases
            // after doing it.

        case 2:
        case 3:
        case 4:
            // Do something else.
            break;
   }

This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.

2
  • dupe of stackoverflow.com/questions/174155/…
    – nawfal
    May 17, 2013 at 21:26
  • It's definitely a double edged sword... if you use it correctly like mentioned below, it's about as clean as code can get. If you use it incorrectly, it's about as ugly as code can get. May 19, 2023 at 19:14

12 Answers 12

128

It may depend on what you consider fallthrough. I'm ok with this sort of thing:

switch (value)
{
  case 0:
    result = ZERO_DIGIT;
    break;

  case 1:
  case 3:
  case 5:
  case 7:
  case 9:
     result = ODD_DIGIT;
     break;

  case 2:
  case 4:
  case 6:
  case 8:
     result = EVEN_DIGIT;
     break;
}

But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.

And please note that I use the C++ FAQ definition of "evil"

2
  • 13
    Just for the sake of Math, 0 is also an even digit.
    – Nighteen
    Jan 1, 2019 at 22:57
  • check if you case have a " break; " on the end Dec 1, 2022 at 18:44
65

It's a double-edged sword. It is sometimes very useful, but often dangerous.

When is it good? When you want 10 cases all processed the same way...

switch (c) {
  case 1:
  case 2:
            ... Do some of the work ...
            /* FALLTHROUGH */
  case 17:
            ... Do something ...
            break;
  case 5:
  case 43:
            ... Do something else ...
            break;
}

The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.

4
  • 3
    If you PC-Lint, you have to insert /*-fallthrough*/, otherwise it complains. Aug 6, 2009 at 22:58
  • 1
    still, if you wanted to make it clear that the behaviour is intentional you might as well do if(condition > 1 && condition <10) {condition = 1}; switch(... saves you cases(for clear looks) plus everyone can see that you really wanted those cases to trigger the same action.
    – Mark
    Jul 25, 2014 at 7:48
  • 4
    This is still terrible coding. The first case should call a function, the second case should call the same function then call a second function. Dec 17, 2014 at 21:21
  • Instead of /* FALLTHROUGH */ you're also allowed to write e.g. // fall through to avoid the compiler warning. But to make the intentional use more obvious you can use __attribute__ ((fallthrough)); Mar 8 at 9:07
24

Have you heard of Duff's device? This is a great example of using switch fallthrough.

It's a feature that can be used and it can be abused, like almost all language features.

2
  • 6
    Note Duff's quoted comment in that article: "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against." Feb 10, 2009 at 0:09
  • 1
    Duff's device is clearly evil
    – Marjeta
    Apr 23, 2013 at 14:23
23

Fall-through is really a handy thing, depending on what you're doing. Consider this neat and understandable way to arrange options:

switch ($someoption) {
  case 'a':
  case 'b':
  case 'c':
    // Do something
    break;

  case 'd':
  case 'e':
    // Do something else
    break;
}

Imagine doing this with if/else. It would be a mess.

3
  • if 'do something' is more than just a little than the switch wil rather be the mess than if/else. With if/else it is everywhere clear which variable is tested. Even this small example wouldn't look so bad with if/else in my eyes
    – grenix
    Jul 5, 2018 at 10:53
  • 1
    this isn't a fall-through example, it's just a multiple case sample
    – woodz
    Sep 9, 2021 at 9:37
  • const foos = ["a","b","c"]; const bars = ["d","e"]; if(foos.includes(x)) { foo(x) } else if (bars.includes(x)) { bar(x) } -- doesn't seem that messy to me.
    – Trevel
    Nov 19, 2022 at 17:20
14

It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit.

An example, to update old versions of some data:

switch (version) {
    case 1:
        // Update some stuff
    case 2:
        // Update more stuff
    case 3:
        // Update even more stuff
    case 4:
        // And so on
}
7

I'd love a different syntax for fallbacks in switches, something like, errr..

switch(myParam)
{
  case 0 or 1 or 2:
    // Do something;
    break;
  case 3 or 4:
    // Do something else;
    break;
}

Note: This would already be possible with enums, if you declare all cases on your enum using flags, right? It doesn't sound so bad either; the cases could (should?) very well be part of your enum already.

Maybe this would be a nice case (no pun intended) for a fluent interface using extension methods? Something like, errr...

int value = 10;
value.Switch()
  .Case(() => { /* Do something; */ }, new {0, 1, 2})
  .Case(() => { /* Do something else */ } new {3, 4})
  .Default(() => { /* Do the default case; */ });

Although that's probably even less readable :P

0
6

As with anything: if used with care, it can be an elegant tool.

However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:

  • it's easy to "forget" a break
  • it's not always obvious for code maintainers that an omitted break was intentional

Good use of a switch/case fall-through:

switch (x)
{
case 1:
case 2:
case 3:
 Do something
 break;
}

Baaaaad use of a switch/case fall-through:

switch (x)
{
case 1:
    Some code
case 2:
    Some more code
case 3:
    Even more code
    break;
}

This can be rewritten using if/else constructs with no loss at all in my opinion.

My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.

3
  • 5
    You can re-write most language constructs using if() and goto... that doesn't justify abandoning an explicit construct though.
    – Shog9
    Oct 9, 2008 at 18:20
  • 2
    I know but switch/case constructs that explicitly use the "case 1: some code case 2: some more code case 3: final code break;" can and should be rewritten using if/else if (my opinion).
    – steffenj
    Oct 9, 2008 at 18:24
  • 3
    Note that switch can be many times faster than a list of if-elses. Switch uses a jump table, or when that is not possible, its conditional jumps will be structured in a decision tree instead of a linear list of conditional jumps. Well-structured nested If-else statements will be, at best, equally fast. Sep 30, 2018 at 2:21
6

It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?

Anywhere I use it, I ensure that it's properly commented:

switch($var) {
    case 'first':
        // Fall-through
    case 'second':
        i++;
        break;
 }
3
  • 2
    The intent is obvious if there is no code for case 'first'. If you code in there, and also want to run the code for case 'second', then the comment is important. But I'd avoid that scenario anyway. Oct 9, 2008 at 18:20
  • 1
    @Joel - I agree completely. In my shop, we've had people put in fallthough comments in such cases, and I think it reduces readability. If there's code there, though, put in the fallthrough comment. Oct 9, 2008 at 18:30
  • What do we mean "not explicit". This is why we break; Other languages do this. It's only an issue for people who have not learned their languages in order. C# demands it for the default case ffs, with no reason to imho.
    – mckenzm
    Sep 11, 2019 at 3:19
5

Using fall-through like in your first example is clearly OK, and I would not consider it a real fall-through.

The second example is dangerous and (if not commented extensively) non-obvious. I teach my students not to use such constructs unless they consider it worth the effort to devote a comment block to it, which describes that this is an intentional fall-through, and why this solution is better than the alternatives. This discourages sloppy use, but it still makes it allowed in the cases where it is used to an advantage.

This is more or less equivalent to what we did in space projects when someone wanted to violate the coding standard: they had to apply for dispensation (and I was called on to advise about the ruling).

2

In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.

That being said, I've found them to be especially helpful when I know that eventually I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.

It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no "reason" to.

1
  • Strictly speaking. The switch statements jump via a set value to a bunch of specific code locations. While the compiler would likely catch such things there is a speed and correctness value to a switch statement over a series of or statements. If p is 0 or p is 1 or p is 2. I actually had to evaluate whether p was 0 and p was 1, rather than jump to the p=2 location in code. Which happened to be identical to p0, and p1. But, I never had to check them.
    – Tatarize
    Nov 18, 2017 at 15:08
2

I don't like my switch statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case statements all do exactly the same thing.

If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.

1

Fall-through should be used only when it is used as a jump table into a block of code. If there is any part of the code with an unconditional break before more cases, all the case groups should end that way.

Anything else is "evil".

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