Site icon Technicalities

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?

55.42706-2.780914
Exit mobile version