UNREACH.ENUM

Unreachable code

Code is unreachable due to the possible value(s) of an enum.

The UNREACH.ENUM checker looks for code that will never be executed because it is guarded by a condition on the enum value, where such a value may not be possible to achieve. This is true for a strongly-typed enumeration. The C-style enum is represented as an integer, and, should it be assigned a garbage value. In the example below, the third branch can be executed.

You can enable the UNREACH.ENUM checker when you expect there will be unreachable code for strongly-typed enums. You can disable the UNREACH.ENUM checker when the code uses C-style enums that can be expected to hold a garbage value and where you deliberately want to use the value in conditions. You can still check for more general cases of unreachable code with the UNREACH.GEN checker.

Vulnerability and risk

Unreachable code due to a condition on an enum value can cause confusion during code maintenance and/or code reviews.

Vulnerable code example

Copy
  enum class E {
      E1, E2
  };
  
  void f1();
  void f2();
  void f3();
  
  void foo(E e)
 {
     if (e == E::E1) {
         f1();
     } else if (e == E::E2) {
         f2();
     } else {
         f3();
     }
 }

In this case, Klocwork reports an UNREACH.ENUM issue, indicating that the call to f3() may never be executed. When using a strongly typed enum in the conditional statement above, the else branch is marked as unreachable because in the strongly typed world, an object of the type enum can only have certain discrete values possible(E1 or E2). In real world code, enum is represented as an integer, and if the enum is assigned a garbage value, the third branch can be executed.