Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

To avoid unexpected behavior, the value being converted must be inside of the range of enumeration values. Furthermore, if it is necessary to check for out-of-range values dynamically, it must be done before the conversion.

Noncompliant Code Example (Bounds

...

Checking)

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
bgColor#FFCCCC
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
}

Compliant Solution (Bounds

...

Checking)

This compliant solution checks for an out-of-bounds condition before the conversion to guarantee there is no unspecified result.

Code Block
bgColor#ccccff
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);

Noncompliant Code Example (Switch

...

Statement)

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
bgColor#ffcccc
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
}

Compliant Solution (Switch

...

Statement)

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
bgColor#ccccff
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
}

Noncompliant Code Example (For

...

Loop)

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.

...

Bibliography

Wiki Markup
\[[Becker 092009|AA. Bibliography#Becker 09]\] Section 7.2, "Enumeration declarations"

...