99

I am a bit puzzled on whenever or not to include break after the last case, often default.

switch (type) {
    case 'product':

        // Do behavior

        break;
    default:

        // Do default behavior

        break; // Is it considered to be needed?
}

breaks sole purpose is in my understanding to stop the code from running through the rest of the switch-case.

Is it then considered more logical to have a break last due to consistency or skip having it due to the break applying no functional use whatsoever? Both are logical in different ways in my opinion.

This could to a certain degree be compared with ending a .php file with ?>. I never end with ?> mostly due to the risk of outputting blank spaces, but one could argue that it would be the logical thing to end the file with.

Robin Castlin
  • 1,199
  • 1
  • 8
  • 11

3 Answers3

161

break isn't technically needed after the last alternative (which, mind you, doesn't have to be default: it is perfectly legal, and sometimes even useful to put the default branch first); whether your code falls through the end of the switch statement or breaks out at the end of its last branch has the same result.

However, I'd still end every branch, including the last one, with a return or break statement, for three reasons:

  1. Refactorability. If all your branches end with break or return, you can reorder them without changing the meaning. This makes it less likely for such a reordering to introduce a regression.
  2. Consistency, and Least Surprise. Consistency says your branches should end consistently, unless they are actually different in meaning. The Principle of Least Surprise dictates that similar things should look similar. Ending the last branch of a switch block exactly like the preceding ones fulfills both, which makes for easier reading and understanding. If you leave out the explicit break, the last branch will be optically different (which is especially important for quick scanning), and in order to see that it's really not different, the reader has to descend to the nitty-gritty level of reading individual statements.
  3. Protecting yourself. If you make a habit of ending all your switch branches with a break, it will become automatic after a while, and you'll be less likely to accidentally forget it where it does matter. Training yourself to expect the break at the end of every branch also helps detecting missing break statements, which is great for debugging and troubleshooting.
tdammers
  • 52,406
  • 14
  • 106
  • 154
  • Thanks for your insight in this! Will `break` last case aswell :) – Robin Castlin Jun 17 '13 at 11:50
  • 7
    In C#, `break` (or other control-flow statement that exits the `case`) *is* technically needed after the last alternative. – dan04 Jun 17 '13 at 15:43
  • 4
    @dan04: yes, good point. C# is an exception here, and it's probably because the language designers knew about the problems with `switch` fall-through in existing languages and wanted to prevent them. The rules C# imposes pretty much match the recommendations from my answer. – tdammers Jun 17 '13 at 20:10
  • What language are you talking about specifically? C? C++? C#? Java? PHP? – svick Jun 20 '13 at 19:18
  • @svick: all of them, to varying degrees. C set the standard back in the days, and C++, Java, JavaScript and PHP use mostly the same rules. C# is a bit different in that it disallows fall-through, but otherwise, the same applies. – tdammers Jun 20 '13 at 23:03
  • 2
    A good compiler would treat the final `break` as a NO-OP instead of generating a `jmp` to the next instruction, correct? – Nathan Osman Jul 15 '13 at 19:06
12

Given the ambiguity that exists around the use of switch-case in most languages, when using it I would suggest always using a break statement, except when it is explicitly and by design not wanted.

Partly this is because is makes every case call look the same, which in my opinion would improve readability. But it also means if someone (even you) chooses to insert a case after the last one at a later stage, they don't need to concern themselves with checking the prior block, which could help reduce bugs when adding new code.

  • 7
    When I want one case to fall-through to the next (and it isn't the degenerate case of `case foo: case bar: ...`) I put an explicit comment in that I want the fall-through to happen. Makes it much clearer. – Donal Fellows Jun 17 '13 at 18:18
  • 3
    Yes like a simple comment `// no break` in place of `break;` – Pacerier Oct 08 '13 at 12:10
  • 2
    Or a `[[fallthrough]]` attribute in case of C++. – Ruslan Feb 22 '18 at 13:03
1

There is no break necessary after the last case. I use the word "last" (not default )because it is not necessary default case is the last case.

switch(x)
{
case 1:
//do stuff
break;

default:
//do default work
break;

case 3:
//do stuff

}

And we know, a break is necessary between two consecutive cases. Sometimes, I use if(a!=0) in my code for more readability when others refer my code. I can choose to use if(a), that would be a matter of my choice

Suvarna Pattayil
  • 559
  • 1
  • 4
  • 8
  • 5
    For me that would mean a "always use break", just in case some programmer added a new `case` at the end of your `switch` without checking that the `break` did exist (it would be that programmer's fault, but still better be safe -if for any reason, because you could be that programmer in 6 months-) – SJuan76 Jun 17 '13 at 09:41
  • @SJuan76 Yes,I agree, better safe than sorry, if you want to keep a safeguard for future errors, you must include one at the end. – Suvarna Pattayil Jun 17 '13 at 09:43
  • 1
    With that argument in mind, you might aswell argue to always have `, ` in the end of arrays in case a new value is inserted. However that breaks some codes and generally looks ugly :) – Robin Castlin Jun 17 '13 at 09:56
  • 1
    @Robin Putting in a comma is different. If it is not there and someone adds a new value to an array then they will get a compile error. However there will be no compile error if the previous case statement is missing a break - so it would be possible for this to be missed and cause run-time errors. – Keith Miller Jun 17 '13 at 10:19
  • @RobinCastlin Provided the language allowed you to put a `,` . Incase, `default` was designed to be the last case . Maybe the language would consider a `break` after it as an error. Assuming `break` was allowed as a differentiator ONLY between two cases. – Suvarna Pattayil Jun 17 '13 at 10:23
  • Going off topic, but I prefer to put a comma after the last item in an array (for languages it is legal to do so). I prefer this because if I add a new element on the next line in the future, I'm only changing one line. This reduces the diff when looking at what changed. It's a very minor point, but anything I can do to minimise irrelevant "noise" in the diffs will help people see the important changes. So, of course, the newly added element gets a comma too - ready for the next addition! – Geoff Hackworth Jun 19 '13 at 20:33