Enumeration types in C map to integers. The normal expectation is that each enumeration type member is distinct. However, there are some non-obvious errors that are commonly made that cause multiple enumberation type members to have the same value.
In this non-compliant code example, numeration type members can be assigned explicit values:
enum {red=4, orange, yellow, green, blue, indigo=6, violet};
|
It may not be obvious to the programmer (though it is fully specified in the language) that yellow and indigo have been declared to be identical values (6), as are green and violet (7).
Enumeration type declarations must either
enum {red, orange, yellow, green, blue, indigo, violet};
|
enum {red=4, orange, yellow, green, blue, indigo, violet};
|
enum {red=4, orange=5, yellow=6, green=7, blue=8, indigo=6, violet=7};
|
It is also advisable to provide a comment explaning why multiple enumeration type members are being assigned the same value so that future maintainers don't mistakenly identify this as an error.
Failing to ensure that constants within an enumeration have unique values can result in unexpected logic results.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
INT09-A |
1 (low) |
1 (unlikely) |
3 (low) |
P3 |
L3 |
Examples of vulnerabilities resulting from the violation of this recommendation can be found on the CERT website.
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.2.2, "Enumeration specifiers" \[[MISRA 04|AA. C References#MISRA 04]\] Rule 9.3 |