This question in mainly pointed at C/C++, but I guess other languages are relevant as well.
I can’t understand why is switch/case still being used instead of if/else if. It seems to me much like using goto’s, and results in the same sort of messy code, while the same results could be acheived with if/else if’s in a much more organized manner.
Still, I see these blocks around quite often. A common place to find them is near a message-loop (WndProc…), whereas these are among the places when they raise the heaviest havoc: variables are shared along the entire block, even when not propriate (and can’t be initialized inside it). Extra attention has to be put on not dropping break’s, and so on…
Personally, I avoid using them, and I wonder wether I’m missing something?
Are they more efficient than if/else’s?
Are they carried on by tradition?
Summarising my initial post and comments – there are several advantages of
switchstatement overif/elsestatement:Cleaner code. Code with multiple chained
if/else if ...looks messy and is difficult to maintain –switchgives cleaner structure.Performance. For dense
casevalues compiler generates jump table, for sparse – binary search or series ofif/else, so in worst caseswitchis as fast asif/else, but typically faster. Although some compilers can similarly optimiseif/else.Test order doesn’t matter. To speed up series of
if/elsetests one needs to put more likely cases first. Withswitch/caseprogrammer doesn’t need to think about this.Default can be anywhere. With
if/elsedefault case must be at the very end – after lastelse. Inswitch–defaultcan be anywhere, wherever programmer finds it more appropriate.Common code. If you need to execute common code for several cases, you may omit
breakand the execution will “fall through” – something you cannot achieve withif/else. (There is a good practice to place a special comment/* FALLTHROUGH */for such cases – lint recognises it and doesn’t complain, without this comment it does complain as it is common error to forgotbreak).Thanks to all commenters.