Main Content

AUTOSAR C++14 Rule A7-2-4

In an enumeration, either (1) none, (2) the first or (3) all enumerators shall be initialized

Description

Rule Definition

In an enumeration, either (1) none, (2) the first or (3) all enumerators shall be initialized.

Rationale

In an enumeration, you can explicitly assign values to one or more enumerators and leave the compiler to deduce the remaining values. However, mixing explicit and implicit assignments can cause confusion for developers or code reviewers.

Polyspace Implementation

The rule checker reports violations on enum definitions if some of the enumerators are assigned explicit values, except the following cases:

  • The first enumerator is assigned an explicit value.

  • All enumerators are assigned an explicit value.

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 class mapEvents: std::uint32_t //Noncompliant
{
   ADD,
   REMOVE,
   MOVE = 10,
   COPY
};

enum class vectorEvents: std::uint32_t //Compliant
{
   ADD = 1,
   REMOVE = 2,
   MOVE = 3,
   COPY = 4
};

enum class listEvents: std::uint32_t //Compliant
{
   ADD,
   REMOVE,
   MOVE,
   COPY
};

enum class setEvents: std::uint32_t //Compliant
{
   ADD = 1,
   REMOVE,
   MOVE,
   COPY
};

In this example, the definition of the enumeration mapEvents is noncompliant because only one of several enumerators is explicitly assigned a value, and the assigned enumerator is not the first one.

The definitions of the following enumerations are compliant:

  • vectorEvents is compliant because all enumerators are explicitly assigned.

  • listEvents is compliant because none of the enumerators are explicitly assigned.

  • setEvents is compliant because only the first enumerator is explicitly assigned.

Check Information

Group: Declaration
Category: Required, Automated

Version History

Introduced in R2019a