3.4.5. Switches vs. If-Else Ladders

Time: 00:02:33 | Download: Large, Large (CC) Small | Streaming Streaming (CC) | Slides (PDF)

Switches and if-else ladders provide essentially the same multi-branching logic. Each has a sequence of conditionally executed statements based on conditions that are, in turn, a function of the program's current state (i.e., the statements are selected based on the current values of some program variables).

char	choice;
	. . .
switch (choice)
{
	case 'A' :
		. . .
		break;
	case 'B' :
		. . .
		break;
	case 'C' :
		. . .
		break;
	default :
		. . .
		break;
}

char	choice;
	. . .
if (choice == 'A')
{
	. . .
}
else if (choice == 'B')
{
	. . .
}
else if (choice == 'C')
{
	. . .
}
else
{
	. . .
}
Simple multi-way branch options. In simple multi-way branching situations, choosing between a switch statement and an if-else ladder is a matter of taste and personal programming style.

If-else ladders are typically more powerful and flexible than switches. Conversely, switches are less complex, are often a bit more compact, and are often a little more efficient than are if-else ladders. Programmers can always replace a switch statement with an if-else ladder, so the choice is largely a matter of personal taste and style. If both control structures perform the same task, it's only natural to ask, "Why have both control statements?" Figure 2 compares the features of the two control statements.

  switch if-else ladder
Data integers only (char, short, int, and long) all valid data types a
Relational Operations implied == (Figure 2) ==, <, <=, >, >= b
Logical Operations implied logical-OR only (Figure 4) &&, ||, ! c
Test Expression One expression (often a single variable) only Each branch requires a different expression, optionally based on different variables
Expression Complexity Test expression only compared with constants Test expressions compared to constants, variables, function calls, and other expressions
The expressive power and flexibility of switches vs. if-else ladders.
  1. Although not covered here, this includes objects with appropriate member functions
  2. Permits simple ranges, e.g., counter < 10
  3. Permits arbitrarily complex tests; range tests are very common: inclusive ranges: 0 <= score && score <= 100 and exclusive ranges: height < 3 || height > 15
While it's always possible to replace a switch with an if-else ladder, it's not always possible to replace a ladder with a switch.