The case of the switch

Please look at the following code snippet and tell me what is wrong with it. No it contains no errors, just something really dumb that shows that the programmer does not understand the switch construct:

switch(foo)
{
     case 1:
     // do something
     break;
 
     case 2:
     // do something
     break;
 
     default:
     // do something
     break;
}

Do you see what I’m talking about? Come on, look at it!

If you couldn’t spot it, shame on you. Look at the default block. Why do we have a break there? The break statement is only there to prevent rolling down the the next case. If you are in the default case, which also happens to be the last case of the switch you are done. There is nothing below default it that can be executed. There is no need to put that break there!

And yet every book, online tutorial, and example I see put it there. Who the hell stated it? Why is everyone blindly copying this pattern? Is it for consistency?

Putting a break on a default statement is not wrong. It is syntactically correct. But that does not mean it does not look dumb as hell when you do it :P

This entry was posted in Uncategorized and tagged . Bookmark the permalink.



One Response to The case of the switch

  1. It provides nice symmetry and consistency of all the cases. Compiler optimizations would likely toss it out anyway, so there wouldn’t be a performance penalty. It might be helpful for future maintenance in, say pattern matching replacement.

    Personally I like it there.

    Reply  |  Quote

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>