This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 10.2.1 - An enumeration shall be defined with an explicit underlying type
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
The underlying type of an enum is explicit when its declaration has an enum-base.
Additionally, an explicit or implicit enumerator value shall not be the result of a narrowing conversion.
Note: the C++ Standard states that any program that violates this additional requirement is ill-formed. However, it is known that
some compilers do not issue a diagnostic.
Rationale
When an enum is defined without an enum-base:
- If the
enum is unscoped, the underlying type is implementation-defined, with the only restriction being that the
type must be able to represent the enumeration values; or
- If the
enum is scoped, it will implicitly have an underlying type of int.
In both cases, using an explicit underlying type ensures that this type is obvious to the user, reducing the risk of an operation on enumerators
leading to unwanted integer overflows.
Exception
The underlying type does not have to be specified when:
- All of the enumerators in an enumeration use their default values — these enumerators are typically used as symbolic values, meaning the
underlying type is not important (M23_061: MISRA C++ 2023 Rule 10.2.3 restricts which operations are permitted for such types); or
- An enumeration is declared in an
extern "C" block — i.e. the enumeration is intended to be used with C code.
Example
enum class Enum1 : int8_t // Compliant
{
E0 = 1,
E1 = 2,
E2 = 4
};
enum class Enum2 // Non-compliant - no explicit underlying type
{
E0 = 0,
E1,
E2
};
The following example will be reported as ill-formed by a conforming compiler.
enum class Enum3 : uint8_t // Non-compliant - cannot represent value for E2
{ // Implicit value is the result of wrapping
E0,
E1 = 255,
E2
};
enum class Enum4 // Compliant by exception #1
{
E0,
E1,
E2
};
extern "C"
{
enum Enum5 // Compliant by exception #2
{
E7_0 = 0,
E7_1,
E7_2
};
}
Copyright The MISRA Consortium Limited © 2023