...
This noncompliant code example attempts to check whether a given value is within the range of acceptable enumeration values. However, it is doing so after casting to the enumeration type, which may not be able to represent the given integer value. On a two's complement system, the valid range of values that can be represented by enum_type
EnumType
are [0..3], so if a value outside of that range were passed to f()
, the cast to enum_type
would EnumType
would result in an unspecified value, and using that value within the if
statement results in unspecified behavior.
Code Block |
---|
|
enum enum_typeEnumType {
E_AFirst,
E_BSecond,
E_CThird
};
void f(int int_varintVar) {
enum_type enum_varEnumType enumVar = static_cast<enum_type>(int_varcast<EnumType>(intVar);
if (enum_varenumVar < E_AFirst || enum_varenumVar > E_CThird) {
// Handle error
}
} |
Compliant Solution (Bounds Checking)
...
Code Block |
---|
|
enum enum_typeEnumType {
E_AFirst,
E_BSecond,
E_CThird
};
void f(int int_varintVar) {
if (int_varintVar < E_AFirst || int_varintVar > E_CThird) {
// Handle error
}
enum_type enum_varEnumType enumVar = static_cast<enum_type>(int_varcast<EnumType>(intVar);
}
|
Compliant Solution (Scoped Enumeration)
...
Code Block |
---|
|
enum class enum_typeEnumType {
E_AFirst,
E_BSecond,
E_CThird
};
void f(int int_varintVar) {
enum_type enum_varEnumType enumVar = static_cast<enum_type>(int_varcast<EnumType>(intVar);
} |
Compliant Solution (Fixed Unscoped Enumeration)
...
Code Block |
---|
|
enum enum_typeEnumType : int {
E_AFirst,
E_BSecond,
E_CThird
};
void f(int int_varintVar) {
enum_type enum_varEnumType enumVar = static_cast<enum_type>(int_varcast<EnumType>(intVar);
} |
Although similar to the previous compliant solution, the previous compliant solution differs from the noncompliant code example in the way the enumerator values are expressed in code and what implicit conversions are allowed. The previous compliant solution requires a nested name specifier to identify the enumerator (for example, enum_typeEnumType::E_AFirst
) and will not implicitly convert the enumerator value to int
. As with the noncompliant code example, this compliant solution does not allow a nested name specifier and will implicitly convert the enumerator value to int
.
...