Applying the unary minus operator to an unsigned variable or expression will always yield another unsigned expression. More plainly, in some cases
the operation itself is meaningless, and in some other cases the result will be unexpected. In all cases it is bad practice. Therefore the unary minus
operator should not be applied to unsigned variables or expressions.
Noncompliant Code Example
uint8_t a = -1U;
int32_t b = -a; // Noncompliant; b is assigned -255
uint32_t c = 1U;
int64_t d = -c; // Noncompliant; d is assigned MAX_UINT
This rule ignores
-1U because it is commonly used as shorthand for
- MISRA C:2004, 12.9 - The unary minus operator shall not be applied to an expression whose underlying type is unsigned.
- MISRA C++:2008, 5-3-2 - The unary minus operator shall not be applied to an expression whose underlying type is unsigned.
- MISRA C:2012, 10.1 - Operands shall not be of an inappropriate essential type