No trivial switch statements¶
ID: cpp/trivial-switch
Kind: problem
Security severity:
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
switch
statement can be removed.If there is just one default case, the
switch
keyword, thedefault
keyword, and the subsequent colon can all be removed.If there is just one non-default case, the
switch
statement can be turned into anif
statement.If there is one default case and one non-default case, the
switch
statement can be turned into anif
/else
statement.
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.