Main Content

MISRA C++:2023 Rule 11.6.3

Within an enumerator list, the value of an implicitly-specified enumeration constant shall be unique

Since R2024b

Description

Rule Definition

Within an enumerator list, the value of an implicitly-specified enumeration constant shall be unique.

Rationale

Repeated implicit values in an enumerator list can indicate programmer oversight.

You can have both explicitly and implicitly-specified enum constants in an enumerator list. For instance, in the example below, the enum constant ERR_BUFFER_OVERFLOW has the explicitly-specified value 0 while the constant ERR_NON_INITIALIZED has the implicitly-specified value 1.

enum ERRVALUES
{
    ERR_BUFFER_OVERFLOW = 0,
    ERR_NON_INITIALIZED
};
When you mix the two kinds of specifications, an implicitly-specified enum constant can accidentally end up with the same value as an explicitly-specified constant. This replication is usually unintentional and might lead to unexpected results.

Polyspace Implementation

The rule checker reports a violation if an implicitly-specified enum constant has the same value as another constant in the same enumerator list. The violation is reported on the enum variable name. The message associated with the violation specifies the names of two enum constants that have the same 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

In this example, the enumeration ERRVALUES violates the rule because one of its implicitly-specified constants ERR_NON_INITIALIZED has the same value 1 as the explicitly specified constant ERR_BUFFER_UNDERFLOW.

namespace errorValues
{
    enum ERRVALUES                   // Noncompliant
    {
        ERR_BUFFER_OVERFLOW = 0,
        ERR_NON_INITIALIZED,
        ERR_PARTIALLY_INITIALIZED,
        ERR_BUFFER_UNDERFLOW = 1
    };
}

namespace bufferOperations {        // Compliant
    enum BUFFER_ERRVALUES
    {
        ERR_BUFFER_OVERFLOW = 0,
        ERR_NON_INITIALIZED,
        ERR_PARTIALLY_INITIALIZED,
        ERR_BUFFER_UNDERFLOW = 3
    }; 
}

Check Information

Group: Declarators
Category: Required

Version History

Introduced in R2024b