Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to put break after the last label of a switch statement?

Surely the compiler knows that it's the last label of the switch statement?

like image 247
CJ7 Avatar asked Aug 11 '10 04:08

CJ7


2 Answers

Having a break after your switch's final case statement is good defensive programming. If, perhaps in the future, another case statement is added below, it removes the risk of the program's flow falling through from the case above.

like image 158
Chris Fulstow Avatar answered Sep 17 '22 13:09

Chris Fulstow


It's because in C++ this is what happens:

switch(a)
{
     case 1:
        // do stuff

     case 2:
        // do other stuff
}

If a is 1, then - according to C++ rules - both "do stuff" and "do other stuff" would happen. So that C++ programmers coming to C# do not get tripped up (and to make code clearer all 'round), C# requires that you explicitly specify whether you want to break or fall through to a different label.

Now, as for why you need the break on the last block, that's a simple matter of consistency. It also make re factoring easier: if you move the cases around, you don't suddenly end up with errors because of a missing break statement. Also, what happens when you want to add another label, etc, etc.

like image 29
Dean Harding Avatar answered Sep 20 '22 13:09

Dean Harding