Main Content

MISRA C++:2008 Rule 6-4-5

An unconditional throw or break statement shall terminate every non - empty switch-clause

Description

Rule Definition

An unconditional throw or break statement shall terminate every non - empty switch-clause.

Rationale

If a throw or break statement is not used at the end of a switch-clause, control flow falls into the next switch-clause. If unintentional, this behavior might cause unexpected results. Using a throw or break statement helps to prevent unintentional fall-through behavior. Use a throw or break statement as the last statement of each case-clause and the default-clause.

Using an empty case-label is acceptable when utilizing fall-through to group together multiple clauses that otherwise require identical statements.

Polyspace Implementation

Polyspace® raises this defect whenever a case-label contains any statements and a throw or break statement is not the final statement of the case-label.

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

expand all

#include <cstdint>

int x, y = 2;

int example(int x)	 
{
    switch (x) { //Noncompliant error shows here
    case 0:              //Compliant empty fall through
    case 1:
        break;           //Compliant break
    case 2:
        x = y ^ 2;       //Unintentional fall through
    case 3:              //Compliant throw
        throw;

    default:             //Compliant break
        break;
    }

    return x;
}

Because case 2 does not contain a throw or break statement, it falls over into case 3. This type of fall through is noncompliant.

Because it is an empty case-label, Case 0 will fall through to case 1. This is a compliant empty case-label fall through.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b