Alex Rivera | Logout

Why use the switch statment instead of if else statments?

Asked 2010-02-02T15:47:33.453
9

Switches seem so useless as they can be replaced with if-else statements, which can do much more than just match a char/int/enum etc. I can only think of one good use for a switch, and that would be for interpreting command line args.

What are some realistic uses for a switch statement?

Edit
Report

2 Answers

9

I use switches when I am using an enum to dictate what actions my method should take. It helps when the actions are mutually exclusive.

answered 2010-02-02T15:49:59.090
0

It may be easier for the compiler to turn a switch statement into a dispatch table than it would be to turn the equivalent if/else soup into a dispatch table. If (and only if) that's true, you should then have O(1) dispatch to the relevant code, instead of O(log n) (or O(n), if the if/else soup is badly written).

In some (although not all) cases it may also be easier to check that you've covered the necessary tests using switch than a wodge of if/else.

answered 2010-02-02T15:55:54.570

Your Answer