This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.3.1 - The built-in unary - operator should not be applied to an expression of unsigned type
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
This rule applies to the type of an expression before any integral promotion.
Rationale
Applying the built-in unary - operator to an expression whose promoted type is unsigned generates a result of the same unsigned
type, which may not meet developer expectations.
The result of applying the unary - operator to an expression whose type is unsigned prior to integral promotion will only be
negative when the promoted type is signed. The promoted type depends on the operand’s rank and the implemented integer sizes.
Example
The following example assumes that int is 32 bits.
void f( int32_t a );
void f( uint32_t a );
void g( uint32_t x, uint16_t y )
{
f( -x ); // Non-compliant - calls f( uint32_t a )
f( -y ); // Non-compliant - calls f( int32_t a )
}
Copyright The MISRA Consortium Limited © 2023