Main Content

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

The condition of a switch statement shall not have bool type

Description

Rule Definition

The condition of a switch statement shall not have bool type.

Rationale

Switch statements that have a bool condition might cause confusion or mistakes not caught by the compiler. If statements are better suited to handling bool evaluations. Use If...else statements in place of switch statements that have a bool condition.

Polyspace Implementation

Polyspace® raises this defect whenever a switch-case conditional results in a bool.

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 = 10;

int example(int x)
{
    switch (x > 0) { //Noncompliant
    case true:
        x += 10;
        break;

    case false:
        x -= 10;
        break;

    default:
        x = 0;
        break;
    }

    return x;
}

Because the switch statement condition x > 0 results in a bool, Polyspace marks it as noncompliant.

Use the following if statement in place of the above switch-case:

#include <cstdint>

int x = 10;

int example(int x)
{
    if (x > 0) {
        x += 10;
    } else if (x <= 0) {
        x -= 10;
    } else {
        x = 0;
    }

    return x;
}

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b