Main Content

MISRA C++:2023 Rule 7.0.1

There shall be no conversion from type bool

Since R2024b

Description

Rule Definition

There shall be no conversion from type bool.

Rationale

Logical errors can occur when a boolean value is implicitly converted to another type. These converted values can then be used in contexts where they were not intended to be used, leading to subtle bugs that can be difficult to diagnose. Additionally, this rule helps identify scenarios where a bitwise operator such as | or & has been accidentally used instead of a logical operator such as || or && because using bitwise operators instead of logical operators can result in conversions from type bool.

Polyspace Implementation

The rule checker reports a violation when you perform a conversion from type bool, including integer promotion or arithmetic conversions. An exception occurs when assigning a boolean to a bit-field of length 1. In this case, a false value is converted to 0 and a true value is converted to 1.

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

int example1()
{
    bool flagA = true;
    bool flagB = false;

    if (flagA & flagB)      //Noncompliant
    {
        //do something
    }

    if (flagA && flagB)     //Compliant
    {
        //do something
    }

    switch (flagB)          //Noncompliant
    {
    case 0:
        //do something
        break;
    case 1:
        //do something
        break;
    default:
        break;
    }
}

In this example:

  • if (flagA & flagB) is noncompliant due to the use of the bitwise operator &. Using & causes a conversion of flagA and flagB to integers. Use the logical operator && instead.

  • switch (flagB) is noncompliant. Using flagB as the switch expression causes flagB to be converted to an integer. In this case, you can replace the switch statement with an equivalent if statement.

Check Information

Group: Standard Conversions
Category: Required

Version History

Introduced in R2024b