20 Dec 2011 broonie   » (Journeyer)

What’s wrong with switch statements?

Recently I’ve been noticing a surprising pattern in code I’m reviewing for the kernel. A lot of people seem to have taken to writing code that I’d expect to look like this:

switch (thing) {
case VALUE:
        /* Stuff */
        break;
case BAR:
        /* Nonsense */
        break;
default:
        /* Whatever */
        break;
}

with if statements instead:

if (thing == VALUE) {
        /* Stuff */
} else if (thing == BAR) {
        /* Nonsense */
} else {
        /* Whatever */
}

(where stuff, nonsense and whatever are usually a bit larger). I really don’t understand where this has come from – the if based form isn’t nearly so idiomatic for selecting between a range of values and this seems to have come from nowhere pretty much. Is there some code base out there where this is common practice or something?

Syndicated 2011-12-20 13:24:55 from Technicalities

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!