Main Content

MISRA C:2012 Rule 12.4

Evaluation of constant expressions should not lead to unsigned integer wrap-around

Description

Note

Using Code Prover for checking coding rules is no longer supported. See Version History.

Rule Definition

Evaluation of constant expressions should not lead to unsigned integer wrap-around.

Rationale

Unsigned integer expressions do not strictly overflow, but instead wraparound. Although there may be good reasons to use modulo arithmetic at run time, intentional use at compile time is less likely and might imply logic errors.

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 might depend on your compiler.

Polyspace does not report a violation when a bitwise shift of 1U could result in a wraparound.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#define DELAY        1000000000u
#define WIDTH        4000000000u

static void fixed_pulse ( void )
{
   int off_time32 = DELAY + WIDTH;    /*Noncompliant*/
   //...
}


static void f4 ( void )
{   const int c = 0xffffffffu;
    int y = c + 1u;                 /* Compliant*/

    //...
}

In this example, the constant expressions DELAY + WIDTH; might lead to wraparounds when compiled with the standard C compiler. Polyspace flags this expression. If you compile this code with other compilers such as GCC, the expression c+1u might show violations of this rule.

Check Information

Group: Expressions
Category: Advisory
AGC Category: Advisory

Version History

expand all