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 { . . . } |
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 |
counter < 10
0 <= score && score <= 100
and exclusive ranges: height < 3 || height > 15