MISRA C++:2008 Rule 6-4-3
A switch statement shall be a well-formed switch statement
Description
Rule Definition
A switch statement shall be a well-formed switch statement.1
Rationale
In addition to the C++ standard syntax rules, MISRA defines their own syntax rules for creating well-formed switch statements. These additional syntax rules create a consistent structure for switch statements.
The additional MISRA syntax rules include:
| Rule | Syntax | 
|---|---|
| switch-statement | switch(condition) {case-label-clause-list
                    default-label-clauseopt} | 
| case-label-clause-list | case-label case-clauseopt case-label-clause-list case-label case-clauseopt | 
| case-label | caseconst-expression | 
| case-clause | case-block-seqopt
                     case-block-seqopt
                     { statement-seqopt
                     {
                      statement-seqopt
                     | 
| default-label-clause | default-label default-clause | 
| default-label default-clause | default: case-clause | 
| case-block | expression_statement compound_statement selection_statement iteration_statement try_block | 
| case-block-seq | case-block case-block-seq case-block | 
These terms from the table are defined as such:
- switch-label— Either a- case-labelor- default-label.
- case-clause— The code between any two- switch-labels.
- default-clause— The code between the- default-labeland the end of the- switchstatement.
- switch-clause— Either a- case-clauseor a- default-clause.
The MISRA C++ switch syntax rules do not include the following
        statements, but do permit them within the compound statements that form the body of a
          switch-clause statement.
- labelled_statement
- jump_statement
- declaration_statement
Polyspace Implementation
The rule checker reports a violation in these situations:
- A statement occurs between the - switchstatement and the first- casestatement.- For instance: - switch(ch) { int temp; case 1: break; default: break; }
- A label or a jump statement such as - gotoor- returnoccurs in the- switchblock.
- A variable is declared in a - casestatement that is outside any block.- For instance: - switch(ch) { case 1: int temp; break; default: break; }
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
| Group: Statements | 
| Category: Required | 
Version History
Introduced in R2013b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
- MISRA C:2004 
- MISRA C:2012 
- MISRA C:2023 
- MISRA C++:2008 
- MISRA C++:2023 
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.