When the value to be compared has a type that is amenable to being switch
'd, and it makes your code more readable, then go ahead and use a switch
. For example,
if (val == 0) {
// do something
} else if (val == 1) {
// do something else
} else if (val == 2) {
// yet another option
} ...
is cluttered and hard to maintain compared to a switch
. Imagine that some day, you don't want to switch on val
but on validate(val)
; then you'd need to change all the conditions.
Also, switch
may be faster than if
/else
sometimes, because a compiler may turn it into either a jump table or a binary search. Then again, a compiler might do the same to a series of if
/else
statements, although that's a more difficult optimization to make because the clauses order might matter and the compiler must be able to detect that it doesn't.