Why is this an issue?
When there is only a single condition to test, you have the option of using either a switch
statement or an if
-else
if
-else
statement. For a larger set of potential values, a switch
can be easier to read, but when the condition being
tested is essentially boolean, then an if
/else
statement should be used instead.
Noncompliant code example
_Bool b = p > 0;
switch (b) { // Noncompliant
...
}
switch (x == 0) { // Noncompliant
...
}
Compliant solution
_Bool b = p > 0;
if (b) {
...
} else {
...
}
if (x == 0) {
...
} else {
...
}
Resources
- MISRA C:2004, 15.4 - A switch expression shall not represent a value that is effectively Boolean
- MISRA C++ 2008, 6-4-7 - The condition of a switch statement shall not have bool type
- MISRA C:2012, 16.7 - A switch-expression shall not have essentially Boolean type