No trivial switch statements¶
ID: cpp/trivial-switchKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - maintainability - readability - external/jsfQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
The following forms ofswitch statement are consideredtrivial:
No cases at all.
Just a default case.
Just one non-default case.
A default case and one non-default case.
Recommendation¶
Either theswitch 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¶
intf(){intval=0;switch(val){//wrong, use an if insteadcase0://...default://...}switch(val){//correct, has 2 cases and a defaultcase0://...case1://...default://...}}
References¶
AV Rule 196,Joint Strike Fighter Air Vehicle C++ Coding Standards. Lockheed Martin Corporation, 2005.