Why is this an issue?
switch
statements are useful when there are many different cases depending on the value of the same expression. For just one or two
cases however, the code will be more readable with if
statements.
Moreover, if
statements are obviously more suitable when the condition of the switch
is boolean.
Here are the rules to count the cases:
-
default
is counted as a case.
- If there is no
default
clause, the case
count is incremented by one (to account for the
else
branch of an equivalent if
).
- All the cases falling through to
default
are not counted (they would all be the else
branch of the
equivalent if
).
Noncompliant code example
switch (variable) {
case 0:
doSomething();
break;
default:
doSomethingElse();
break;
}
Compliant solution
if (variable == 0) {
doSomething();
} else {
doSomethingElse();
}
Resources
- MISRA C:2012, 16.6 - Every switch statement shall have at least two switch-clauses