In an enumeration, it is possible to have several enumerators with the same value. This can be useful in many circumstances. But if that happens
without an explicit choice from the developer, it can also lead to errors that are hard to diagnose.
When an enumerator has no explicit value, its value will be one more than the preceding enumerator. When another enumerator uses the same value,
there are three possibilities:
- The other enumerator also has an implicit value. This rule raises an issue since this collision involves no explicit decision.
- The other enumerator has a value directly defined as equal to an enumerator of this enum. In that case, this rule considers the collision to be
a conscious decision and does not raise an issue.
- The other enumerator has an explicit value defined in another way. In that case, the collision might be accidental, and this rule raises an
issue.
Noncompliant code example
enum color { red = 3, blue, green, yellow = 5 }; // Noncompliant, both green and yellow = 5
Compliant solution
enum color { red = 3, blue, green, yellow }; // Compliant, different values
enum color { red = 3, blue, green = 5, yellow = 5 }; // Compliant, all identical values are non-implicit
enum color { red = 3, blue, green, yellow = green }; // Compliant, yellow is defined as identical to green