This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 5.13.4
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
This rule applies to any integer-literal that exists after preprocessing. It does not apply to user-defined-integer-literals.
An unsigned integer-suffix is required when the type of the integer literal, as specified by the C++ Standard in [lex.icon], is
unsigned.
Note: this rule does not depend on the context in which a literal is used; promotion and other conversions that may be applied to
the value are not relevant in determining compliance with this rule.
Rationale
The type of an integer literal is a potential source of confusion, because it is dependent on a complex combination of factors
including:
- The magnitude of the constant;
- The implemented sizes of the integer types;
- The presence of any suffixes;
- The number base that is used.
For example, the decimal integer literal 32768
always has signed type. However, the integer literal
0x8000
is of type unsigned int
in a 16-bit environment, but of type signed int
in a 32-bit environment. Adding
a U
or u
suffix to the integer literal makes the signedness of the value explicit on a 16-bit platform.
Note: compliance checks against this rule will only be valid if an analysis tool has been configured with the same integer sizes
as the compiler that is being used within the project.
Example
The following examples assume that int
is 16 bits:
auto x = 32768; // Compliant - signed type
auto y = 0x8000; // Non-compliant - unsigned type
uint16_t z = 123; // Compliant - 'u' is not required as '123' is signed
void f( uint16_t ); // #1
void f( int16_t ); // #2
void b()
{
f( 0x8000 ); // Non-compliant - calls #1 as 0x8000 is unsigned
f( 0x8000u ); // Compliant - calls #1
f( 0x7FFF ); // Compliant - calls #2 as 0x7FFF is signed
f( 0x7FFFu ); // Compliant - calls #1
}
Copyright The MISRA Consortium Limited © 2023