According to the C Standard, 6.8.45.23, paragraph 4 [ISO/IEC 9899:20112024],
A switch statement causes control to jump to, into, or past the statement that is the switch body, depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch body. A case or default label is accessible only within the closest enclosing switch statement.
If a programmer declares variables, initializes them before the first case statement, and then tries to use them inside any of the case statements, those variables will have scope inside the switch block but will not be initialized and will consequently contain indeterminate values. Reading such values also violates EXP33-C. Do not read uninitialized memory.
Noncompliant Code Example
...
Using test conditions or initializing variables before the first case statement in a switch block can result in unexpected behavior and undefined behavior 20.
Rule | Severity | Likelihood | Detectable | RepairableRemediation Cost | Priority | Level |
|---|---|---|---|---|---|---|
DCL41-C | Medium | Unlikely | Yes | MediumYes | P4P6 | L3L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||||||||
| Astrée |
| switch-skipped-code | Fully checked | ||||||||||||
| Axivion Bauhaus Suite |
| CertC-DCL41 | Fully implemented | ||||||||||||
| Clang |
| -Wsometimes-uninitialized | |||||||||||||
| CodeSonar |
| LANG.STRUCT.SW.BAD | Malformed switch Statement | ||||||||||||
| Coverity |
| MISRA C 2004 Rule 15.0 MISRA C 2012 Rule 16.1 | Implemented | ||||||||||||
| Cppcheck Premium |
| premium-cert-dcl41-c | |||||||||||||
| Helix QAC |
| C2008, C2882, C3234 | Fully implemented | ||||||||||||
| Klocwork |
| CERT.DCL.SWITCH.VAR_BEFORE_CASE | Fully implemented | ||||||||||||
| LDRA tool suite |
| 385 S | Fully implemented | ||||||||||||
| Parasoft C/C++test |
| CERT_C-DCL41-a | A switch statement shall only contain switch labels and switch clauses, and no other code | ||||||||||||
| PC-lint Plus |
| 527 | Assistance provided | ||||||||||||
| Polyspace Bug Finder |
| CERT C: Rule DCL41-C | Checks for ill-formed switch statements (rule | fully partially covered) | |||||||||||
| PRQA QA-C | |||||||||||||||
| Include Page | PRQA QA-C_v | PRQA QA-C_v | 3234 | Partially implemented | PVS-Studio |
| V622 | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| RuleChecker |
| switch-skipped-code | Fully checked | ||||||||||||
| TrustInSoft Analyzer |
| initialisation | Exhaustively detects undefined behavior (see the compliant and the non-compliant example). |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Bibliography
| [ISO/IEC 9899:20112024] | 6.8.45.23, "The switch Statement" |
...