Missing break of switch case
case
block of switch
statement does not end in a break
, [[fallthrough]]
or explanatory comment
Description
This defect occurs when a case
block of switch
statement does not end in a break
, a [[fallthrough]]
, or a code comment.
If the last entry in the case block is a code comment, for instance:
switch (wt) { case WE_W: do_something_for_WE_W(); do_something_else_for_WE_W(); /* fall through to WE_X*/ case WE_X: ... }
Risk
Switch cases without break statements fall through to the next switch case. If this fall-through is not intended, the switch case can unintentionally execute code and end the switch with unexpected results.
Fix
If you forgot the break statement, add it before the end of the switch case.
If you do not want a break for the highlighted switch case, add a comment to your code to document why this case falls through to the next case. This comment removes the defect from your results and makes your code more maintainable.
In some cases, such as in template functions, the defect checker might ignore the comment at the end of a case statement. A cleaner way to indicate a deliberate fall through to the next case is to use one of these fallthrough
attributes if possible:
[[fallthrough]]
: Available since C++17.[[gnu::fallthrough]]
and[[clang::fallthrough]]
: Available with GCC and Clang compilers.__attribute__((fallthrough))
: Available with GCC compilers.
Examples
Result Information
Group: Good Practice |
Language: C | C++ |
Default: Off |
Command-Line Syntax: MISSING_SWITCH_BREAK |
Impact: Low |
Version History
Introduced in R2016bSee Also
Missing case for switch condition
| Find defects (-checkers)
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)