switch statement without a default clause
ID |
c.correctness.switch_without_default |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
C / C++ |
Description
This switch statement has no default clause. Without a default, values not covered by an explicit case fall through silently, which can hide logic errors and unhandled inputs. Add a default: clause to handle unexpected values explicitly (even if only to assert or log).
Rationale
This switch statement has no default clause. Without a default, values not covered by an explicit case fall through silently, which can hide logic errors and unhandled inputs. Add a default: clause to handle unexpected values explicitly (even if only to assert or log).
The following code illustrates the pattern detected by this rule:
int classify(int n)
{
// FLAGGED: switch statement without a default clause
switch (n) {
case 0:
return 1;
case 1:
return 2;
}
return 0;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.
References
-
https://wiki.sei.cmu.edu/confluence/display/c/MSC01-C.+Strive+for+logical+completeness
-
https://gitlab.com/MISRA/MISRA-C/MISRA-C-2012/Example-Suite (MISRA C:2012 Rule 16.4 - every switch shall have a default label)