Detection of unreachable code is a form of
control flow analysis to find code that can never be reached in any possible program state. In some languages (e.g.
Java) some forms of unreachable code are explicitly disallowed. The optimization that removes unreachable code is known as
dead code elimination. Code may become unreachable as a consequence of transformations performed by an
optimizing compiler (e.g.,
common subexpression elimination). In practice the sophistication of the analysis has a significant impact on the amount of unreachable code that is detected. For example,
constant folding and simple flow analysis shows that the inside of the if-statement in the following code is unreachable: int n = 2 + 1; if (n == 4) { // unreachable } However, a great deal more sophistication is needed to work out that the corresponding block is unreachable in the following code: • include double x = sqrt(2); if (x > 5) { // unreachable } Unreachable code elimination technique is in the same class of optimizations as
dead code elimination and
redundant code elimination. Some languages allow explicitly marking code as unreachable: •
C: via the unreachable() macro (in ) •
C++: via the std::unreachable() function (in ), which is
noreturn •
C#: can be indicated using the System.Diagnostics.Debug class, using the Debug.Fail() method •
Java: usually marked by
throwing the java.lang.AssertionError exception •
Rust: via the unreachable!() macro •
Swift: via fatalError(), or functions returning Never •
Zig: via the unreachable keyword
Unreachability vs. profiling In some cases, a practical approach may be a combination of simple unreachability criteria and use of a
profiler to handle the more complex cases. Profiling in general can not
prove anything about the unreachability of a piece of code, but may be a good
heuristic for finding potentially unreachable code. Once a suspect piece of code is found, other methods, such as a more powerful code analysis tool, or even analysis by hand, could be used to decide whether the code is truly unreachable. ==See also==