No trivial switch statements¶
ID: cpp/trivial-switch
Kind: problem
Severity: recommendation
Precision: high
Tags:
- maintainability
- readability
- external/jsf
Query suites:
- cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
The following forms of switch statement are considered trivial:
- No cases at all.
- Just a default case.
- Just one non-default case.
- A default case and one non-default case.
Recommendation¶
Either the switch statement should be replaced with a simpler control flow structure, or it should be extended to handle more cases. Each trivial form has a different replacement:
- If there are no cases, the
switchstatement can be removed. - If there is just one default case, the
switchkeyword, thedefaultkeyword, and the subsequent colon can all be removed. - If there is just one non-default case, the
switchstatement can be turned into anifstatement. - If there is one default case and one non-default case, the
switchstatement can be turned into anif/elsestatement.
Example¶
int f() {
int val = 0;
switch(val) { //wrong, use an if instead
case 0:
//...
default:
//...
}
switch(val) { //correct, has 2 cases and a default
case 0:
//...
case 1:
//...
default:
//...
}
}
References¶
- AV Rule 196, Joint Strike Fighter Air Vehicle C++ Coding Standards. Lockheed Martin Corporation, 2005.

