Why Switch/Case and not If/Else If?

Summarising my initial post and comments – there are several advantages of switch statement over if/else statement:

  1. Cleaner code. Code with multiple chained if/else if ... looks messy and is difficult to maintain – switch gives cleaner structure.

  2. Performance. For dense case values compiler generates jump table, for sparse – binary search or series of if/else, so in worst case switch is as fast as if/else, but typically faster. Although some compilers can similarly optimise if/else.

  3. Test order doesn’t matter. To speed up series of if/else tests one needs to put more likely cases first. With switch/case programmer doesn’t need to think about this.

  4. Default can be anywhere. With if/else default case must be at the very end – after last else. In switchdefault can be anywhere, wherever programmer finds it more appropriate.

  5. Common code. If you need to execute common code for several cases, you may omit break and the execution will “fall through” – something you cannot achieve with if/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 forgot break).

Thanks to all commenters.

Leave a Comment