A C enumeration defines a type with a finite set of values represented by identifiers known as enumeration constants, or enumerators. An enumerator is a constant integer expression whose value is representable as an int. While the language allows multiple enumerators of the same type to have the same value, it is a common expectation that all enumerators of the same type have distinct values. However, defining two or more enumerators of the same type to have the same value can lead to some nonobvious non-obvious errors.
Noncompliant Code Example
In this noncompliant code example, two enumerators of type Color are assigned explicit values. It may could 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. Since 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:
...
Of these three options, the firstâ”first, "provide no explicit integer assignments," â”is is the simplest and, and consequently, the preferred , approach unless the first enumerator must have non-zero value.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: INT09-CPP. Ensure enumeration constants map to unique values
...
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.7.2.2, "Enumeration specifiers"
\[[Wiki Markup
ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] TR 24772 "CCB Enumerator issues" \[[MISRA 2004|AA. Bibliography#MISRA 04]\] Rule
MISRA Rule 9.3
Bibliography
...
04. Integers (INT) INT11-C. Take care when converting from pointer to integer or integer to pointer