MISRA C++:2023 Rule 10.2.1
Description
Rule Definition
An enumeration shall be defined with an explicit underlying type.
Rationale
If the underlying type of an enumeration is not large enough to accommodate all the values of the enumerators, some enumerators might overflow. The values of these overflowing enumerator might be narrowed to values that already represent other enumerators, resulting in unexpected behavior.
To avoid unexpected narrowing, use appropriate underlying types for enumerations. An underlying type is appropriate if it satisfies all of these requirements:
The underlying type is explicitly specified.
All expressions defining values for the enumerators can be converted to the underlying type without any narrowing.
No enumerator value is too big to be represented by the underlying type.
As exceptions, explicitly specifying an underlying type is not required for these two cases:
All the enumerators in an enumeration use their default values:
Here, all the enumerators ofenum class defaultEnum{ E0, E1, E3 };
defaultEnum
use their default values since no values are specified for any of the enumerators. For these kinds of enumerations, the underlying type is not important.An enumeration is declared in an
extern "C"
block:Enumerations declared withinextern "C"{ enum CStyleEnum{ E1 = 0, E2, E3 }; }
extern "C"
blocks are intended to be used with C code, where this rule does not apply.
Polyspace Implementation
Polyspace® reports violations of this rule if either of these situations occurs:
You declare an enumeration without explicitly specifying an underlying type.
You declare an underlying type for the enumeration but at-least one of its enumerators are out of range for the specified underlying type.
As exceptions, Polyspace does not report violations for these two scenarios:
All the enumerators of an enumeration use their default value.
The enumeration is declared within an
extern "C"
block.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Declarations |
Category: Required |
Version History
Introduced in R2024b