Lably
Skip to content

Unreachable code

Section of code in a program that can never be executed

  • 7 min read
  • 3 chapters

Related on Lably

Through Computer programming, Control flow and Java (programming language)

Unreachable code is sometimes also called dead code, although dead code may also refer to code that is executed but has no effect on the output of a program.

Unreachable code is generally considered undesirable for several reasons:

  • It uses memory unnecessarily
  • It can cause unnecessary use of the CPU's instruction cache
  • Time and effort may be spent testing, maintaining and documenting code which is never used
    • Sometimes an automated test is the only thing using the code.

Unreachable code can have some legitimate uses, like providing a library of functions for calling or jumping to manually via a debugger while the program is halted after a breakpoint. This is particularly useful for examining and pretty-printing the internal state of the program. It may make sense to have such code in the shipped product, so that a developer can attach a debugger to a client's running instance.

Causes

Unreachable code can exist for many reasons, such as:

  • programming errors in complex conditional branches
  • a consequence of the internal transformations performed by an optimizing compiler;
  • incomplete testing of new or modified code
  • Legacy code
    • Code superseded by another implementation
    • Unreachable code that a programmer decided not to delete because it is mingled with reachable code
    • Potentially reachable code that current use cases never need
    • Dormant code that is kept intentionally in case it is needed later
  • Code used only for debugging.

Legacy code is that which was once useful but is no longer used or required. But unreachable code may also be part of a complex library, module or routine where it is useful to others or under conditions which are not met in a particular scenario.

An example of such a conditionally unreachable code may be the implementation of a general string formatting function in a compiler's runtime library, which contains complex code to process all possible arguments, of which only a small subset is actually used. Compilers will typically not be able to remove the unused code sections at compile time, as the behavior is largely determined by the values of arguments at run time.

Sign in to keep reading

2 more chapters are free with a Lably account.

More in From Lably lessons