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

1  enum class E {
2      E1, E2
3  };
5  void f1();
6  void f2();
7  void f3();
9  void foo(E e)
10 {
11     if (e == E::E1) {
12         f1();
13     } else if (e == E::E2) {
14         f2();
15     } else {
16         f3();
17     }
18 }

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.