Expressions and statements
ES.70
Prefer a `switch`-statement to an `if`-statement when there is a choice
Reason
- Readability.
- Efficiency: A
switchcompares against constants and is usually better optimized than a series of tests in anif-then-elsechain. - A
switchenables some heuristic consistency checking. For example, have all values of anenumbeen covered? If not, is there adefault?
Example
void use(int n)
{
switch (n) { // good
case 0:
// ...
break;
case 7:
// ...
break;
default:
// ...
break;
}
}
rather than:
void use2(int n)
{
if (n == 0) // bad: if-then-else chain comparing against a set of constants
// ...
else if (n == 7)
// ...
}
Enforcement
Flag if-then-else chains that check against constants (only).