...
This noncompliant code example attempts to check for an out-of-bounds condition. However, it is doing so after the conversion, so the result of the conversion is unspecified and the statement may have no effect.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A, E_B }; int int_var = -1; enum_type enum_var = static_cast<enum_type>(int_var); if (enum_var < E_A) { // handle error } |
...
This compliant solution checks for an out-of-bounds condition before the conversion to guarantee there is no unspecified result.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A, E_B }; int int_var = -1; if (int_var < E_A || int_var > E_B) { // handle error } enum_type enum_var = static_cast<enum_type>(int_var); |
...
This noncompliant code may result in a truncation of the value of int_var
when converted to type enum_type
, resulting in execution of either case E_A
or E_B
instead of the default case.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A, E_B }; int int_var = 5; switch (static_cast<enum_type>(int_var)) { case E_A: // some action A case E_B: // some action B default: // handle error } |
...
This compliant solution checks for an out-of-bounds condition before the conversion to guarantee that there are no unspecified values and, consequently, no truncation.
Code Block | ||||
---|---|---|---|---|
| ||||
std::cout << "case A" << std::endl; enum enum_type { E_A, E_B }; int int_var = 5; if (int_var < E_A || int_var > E_B) { // handle error } switch (static_cast<enum_type>(int_var)) { case E_A: // some action A case E_B: // some action B default: // handle error } |
...
This noncompliant code may result in an infinite loop instead of the expected behavior of looping through all enumeration values. The violation occurs at the end of the loop, when incrementing enum_var
from the last valid value E_G
produces an unspecified result.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A = 1, E_B, E_C, E_D, E_E, E_F, E_G }; for(enum_type enum_var = E_A; enum_var <= E_G; enum_var = static_cast<enum_var>(enum_var+1)) { // some action } |
...
This compliant solution prevents any out-of-bounds arithmetic on the enumeration type.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A = 1, E_B, E_C, E_D, E_E, E_F, E_G }; for(int i = E_A; i <= E_G; i = i+1) { // some action } |
...