Switch Statement - Advantages and Disadvantages

Advantages and Disadvantages

In some languages and programming environments, the use of a case or switch statement is considered superior to an equivalent series of if else if statements because it is:

  • Easier to debug (e.g. setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability)
  • Easier to read (subjectively)
  • Easier to understand, and therefore
  • Easier to maintain
  • Fixed depth: a sequence of "if else if" statements yields deep nesting, making compilation more difficult (especially in automatically generated code)
  • Faster execution potential
  • Easier to study and write the examination for students

Additionally, an optimized implementation may execute much faster than the alternative, because it is often implemented by using an indexed branch table. For example, deciding program flow based on a single character's value, if correctly implemented, is vastly more efficient than the alternative, reducing instruction path lengths considerably. When implemented as such, a switch statement essentially becomes a perfect hash.

In terms of the control flow graph, a switch statement consists of two nodes (entrance and exit), plus one edge between them for each option. By contrast, a sequence of "if...else if...else if" statements has an additional node for every case other than the first and last, together with a corresponding edge. The resulting control flow graph for the sequences of "if"s thus has many more nodes and almost twice as many edges, with these not adding any useful information. However, the simple branches in the if statements are individually conceptually easier than the complex branch of a switch statement. In terms of cyclomatic complexity, both of these options increase it by k−1 if given k cases.

When implemented with fall-through as the default path, switch/case statements are a frequent source of bugs among even experienced programmers, given that, in practice, the "break" is almost always the desired path, but not the default behavior of the switch/case construct (at least in C and Java).

Read more about this topic:  Switch Statement

Famous quotes containing the word advantages:

    The advantages found in history seem to be of three kinds, as it amuses the fancy, as it improves the understanding, and as it strengthens virtue.
    David Hume (1711–1776)