...
In this noncompliant code example, two enumerators of type Color are assigned explicit values. It may not be obvious to the programmer that yellow and indigo have been declared to be identical values (6), as are green and violet (7). Probably the least dangerous error that can result from such a definition is attempting to use the enumerators as labels of a switch statement. Because all labels in a switch statement are required to be unique, the following code violates this semantic constraint and is required to be diagnosed by a conforming compiler:
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum Color { red=4, orange, yellow, green, blue, indigo=6, violet };
const char* color_name(enum Color col) {
switch (col) {
case red: return "red";
case orange: return "orange";
case yellow: return "yellow";
case green: return "green";
case blue: return "blue";
case indigo: return "indigo"; //* errorError: duplicate label (yellow) */
case violet: return "violet"; //* errorError: duplicate label (green) */
}
}
|
Compliant Solution
To prevent the error discussed of the noncompliant code example, enumeration type declarations must take one of the following forms:
- provide Provide no explicit integer assignments, as in this example:
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum Color { red, orange, yellow, green, blue, indigo, violet };
|
- assign Assign a value to the first member only (the rest are then sequential), as in this example:
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum Color { red=4, orange, yellow, green, blue, indigo, violet };
|
- assign Assign a value to all members so any equivalence is explicit, as in this example:
...
It is also advisable to provide a comment explaining why multiple enumeration type members are being assigned the same value so that future maintainers do not mistakenly identify this form as an error.
Of these three options, the first, "provide providing no explicit integer assignments ," is the simplest and consequently the preferred approach unless the first enumerator must have a nonzero value.
Exceptions
| Anchor | ||||
|---|---|---|---|---|
|
INT09-EX1: In cases where defining an enumeration with two or more enumerators with the same value is intended, the constant expression used to define the value of the duplicate enumerator should reference the enumerator rather than the original enumerators enumerator's value. This practice makes the intent clear to both human readers of the code and automated code analysis tools that detect violations of this guideline and would diagnose them otherwise. Note, however, that it does not make it possible to use such enumerators in contexts where unique values are required (such as in a
switch statement, as discussed earlier)....
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
| CC2.INT09 | Fully implemented | |||||||
| 85 S | Fully implemented | |||||||
| PRQA QA-C |
| 0722 | Fully implemented |
...