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.2 - Unscoped enumerations should not be declared
[dcl.enum] / 2
Category: Advisory
Analysis: Decidable,Single Translation Unit
Rationale
If an unscoped enumeration type is declared, its enumerators may hide an entity declared with the same name in an outer scope.
This may lead to developer confusion.
Using a scoped enumeration restricts the scope of its enumerators' names, which can only be referenced as qualified names. In addition,
its enumerators cannot be implicitly converted to numeric values.
Exception
This rule does not apply to an unscoped enumeration type declared as a class member as any name hiding would be reported as a violation of
M23_029: MISRA C++ 2023 Rule 6.4.1. This idiom was commonly used before scoped enumeration types were introduced.
Example
static int32_t E10 = 5;
static int32_t E20 = 5;
enum E1 : int32_t { E10, E11, E12 }; // Non-compliant - ill-formed as
// E10 already declared
enum class E2 : int32_t { E20, E21, E22 }; // Compliant
void f1( int32_t number );
void f2()
{
f1( 0 );
f1( E11 ); // Implicit conversion from enum to int32_t type
f1( E2::E21 ); // Ill-formed - implicit conversion of scoped enumeration
f1( static_cast< int32_t >( E2::E21 ) ); // Explicit conversion needed
}
class C1
{
public:
enum Cstyle { E10, E20, E30 }; // Compliant by exception
};
Copyright The MISRA Consortium Limited © 2023