Sequences of ifs are fragile and a common cause of error. Chains of if..else if are even worse.
There are three main causes of error:
- Mistyping the check condition
- Omitting an option or options, so that there are conditions not catered for, with unexpected consequences for the code.
- Unintentionally having overlapping conditions.
Example of error 1:
if (a == 0) ...
if (a = 1) ...
if (a == 2) ...
Look at the second check. The effect is that if a is not zero, it will always be set to 1. With a switch statement you can't really do this; you only type the condition once, so you either get it wrong for everything (which will soon become evident) or right for everything.
The second and third kinds of error are possible with switch but less likely, firstly because switch offers a default option and secondly because the layout is much clearer. With chained ifs, you repeatedly type out the whole chec; with switch, you simply type the expected values. Compare:
if (objectX.checkFunc(x - y) == 0) ...
if (objectX.checkFunc(x - y) == 1) ...
to
switch(objectX.checkFunc(x - y) {
case 0: ...
case 1: ...
default: ...
}
But the most important thing I said in all of the above is this: you only type the condition once. Code duplication is always a bad smell. Don't repeat yourself if you have a clean way to avoid it.
Having said all of that, don't forget the break statement. Most other languages which have something like switch do not allow fall-through; in those languages, it is much harder to have overlapping conditions in switch than in a sequence of if statements. In C/C++ this is not the case; accidental fall-through is the most common error with switch.