Main Content

MISRA C++:2023 Rule 8.20.1

An unsigned arithmetic operation with constant operands should not wrap

Since R2024b

Description

Rule Definition

An unsigned arithmetic operation with constant operands should not wrap.

Rationale

Unsigned integer expressions do not strictly overflow, but instead wrap around. Although there may be good reasons to use modular arithmetic at run time, intentional use at compile time is less likely and can indicate logic errors.

This rule applies to built-in arithmetic operations that results in an unsigned integral types. In such operations, the operands are constant expressions.

Polyspace Implementation

Polyspace® flags the constant expressions that might wraparound.

Different compilers might define compile-time constants differently. In the following code, c + 1u is considered a constant expression by GCC compilers, but not by the standard C++ compiler.

const uint16_t c = 0xffffu;
uint16_t y = c + 1u;
Whether you see a violation of this rule in the preceding code depends on your compiler.

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

 
#define BEGIN        0x8000
#define FIN          0xFFFF
#define POS          0x8000
#if ( ( BEGIN + POS ) > FIN )
//....
#endif
#if ((( FIN - BEGIN ) - POS) < 0)   //Noncompliant
//...
#endif

  void fn ( )
  {
    if (( BEGIN + POS ) > FIN) {   // Noncompliant
      //...
    }
  }

In this example, the constant expressions (( FIN - BEGIN ) - POS) and (( BEGIN + POS ) > FIN) can lead to wrap around. Polyspace flag these expressions.

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2024b