Main Content

MISRA C++:2023 Rule 0.0.2

Controlling expressions should not be invariant

Since R2024b

Description

Rule Definition

Controlling expressions should not be invariant.

Rationale

If the controlling expression of an if, for, or while statement has an invariant value, for instance, always evaluates to true or false, the expression is dead code that can be removed without any functional impact. Compilers can sometimes detect these invariant expressions and remove them from the final executable. These invariant expressions typically indicate a programming error and might lead to code inadvertently not executing.

Polyspace Implementation

The rule checker reports violations if the controlling expression of statements such as if, for, or while evaluate to a constant value.

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

In this example:

  • The expression realReading < UINT32_MAX in the function mightExceedStorageCapacity() violates the rule. The expression always evaluates to true because realReading is the product of two uint8_t variables and therefore cannot exceed UINT32_MAX.

  • The expression realReading < UINT8_MAX in the function mightExceedHardwareCapacity() does not violate the rule because the expression does not evaluate to a constant value. Both the if and else branch are reachable.

#include <climits>
#include <cstdint>

bool mightExceedStorageCapacity(uint8_t meterReading, uint8_t scale)
{
    uint32_t realReading = meterReading * scale;
    if (realReading < UINT32_MAX) { //Noncompliant
        return true;
    }
    else {
        return false;
    }
}

bool mightExceedHardWareCapacity(uint8_t meterReading, uint8_t scale)
{
    uint32_t realReading = meterReading * scale;
    if (realReading < UINT8_MAX) { //Compliant
        return true;
    }
    else {
        return false;
    }
}

Check Information

Group: Language Independent Issues
Category: Advisory

Version History

Introduced in R2024b