V2566. MISRA. Constant expression evaluation should not result in an unsigned integer wrap-around.
This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).
This diagnostic rule applies only to code written in C. As specified by the C standard, an overflow of values of unsigned types results in a wrap-around. Using this mechanism in evaluation of expressions at runtime is a well-known practice (unlike signed types, where an overflow leads to undefined behavior).
However, an unsigned integer wrap-around in expressions evaluated at compile time may be misleading.
Example of non-compliant code:
#include <stdint.h>
#define C1 (UINT_MAX)
#define C2 (UINT_MIN)
....
void foo(unsigned x)
{
switch(x)
{
case C1 + 1U: ....; break;
case C2 - 1U: ....; break;
}
}
According to this rule, an unsigned integer wrap-around that occurs when evaluating a constant expression of unsigned type, it will not be treated as an error if the expression will never be evaluated:
#include <stdint.h>
#define C UINT_MAX
....
unsigned foo(unsigned x)
{
if(x < 0 && (C + 1U) == 0x42) ....;
return x + C;
}
The '(C + 1U)' expression resulting in an overflow will not be executed since the 'x < 0' condition is always true. Therefore, the second operand of the logical expression will not be evaluated.
This diagnostic is classified as:
|