Main Content

AUTOSAR C++14 Rule A7-2-3

Enumerations shall be declared as scoped enum classes

Description

Rule Definition

Enumerations shall be declared as scoped enum classes.

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.

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: Declaration
Category: Required, Automated

Version History

Introduced in R2019b