Main Content

MISRA C++:2023 Rule 10.2.2

Unscoped enumerations should not be declared

Since R2024b

Description

Rule Definition

Unscoped enumerations should not be declared.

Rationale

Enumeration values in an unscoped enum can conflict with other identifiers in the same scope as the enum and cause compilation errors. For instance:

enum E: std::int32_t { E0, E1};
std::int32_t E0;

If you scope the enum, such conflicts can be avoided. For instance:

enum class E: std::int32_t { E0, E1};
std::int32_t E0;

Scoping the enum also disallows implicit conversions of the enumeration values to other types.

Polyspace Implementation

Polyspace® reports a violation on enumerations in your code that are not scoped. Unscoped enumerations within a class are not reported as violations of this rule.

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

expand all

#include<cstdint>

enum E1: std::int32_t { E10, E11}; //Noncompliant
// std::int32_t E10; causes compilation errors

enum class E2: std::int32_t { E20, E21}; //Compliant
std::int32_t E20;

In this example, the declaration of unscoped enum E1 is noncompliant. Redeclaring an enumeration value of the unscoped enum causes compilation errors (as shown in the commented line that redeclares the enumeration value E10).

Check Information

Group: Declarations
Category: Advisory

Version History

Introduced in R2024b