## Switch-Statements

**Introduction:** The "switch" or "case" statement is available in a variety of languages. Our switch-statement syntax is shown in Fig. 6.48. There is a selector expression E, which is to be evaluated, followed by n constant values Vi, V2, . . . ,Vn that the expression might take, perhaps including a default "value," which always matches the expression if no other value does.

switch ( E ) {

case V\. Si

case W - S_{2}

case V_{n} _ i : »S_{n}-i

default: 5_{n}

}

**Figure 6.48: Switch-statement syntax**

Translation of Switch-Statements

The intended translation of a switch is code to:

1. Evaluate the expression E.

2. Find the value V} in the list of cases that is the same as the value of the expression. Recall that the default value matches the expression if none of the values explicitly mentioned in cases does.

3. Execute the statement Sj associated with the value found.

Step (2) is an n-way branch, which can be implemented in one of several ways. If the number of cases is small, say 10 at most, then it is reasonable to use a sequence of conditional jumps, each of which tests for an individual value and transfers to the code for the corresponding statement.

A compact way to implement this sequence of conditional jumps is to create a table of pairs, each pair consisting of a value and a label for the corresponding statement's code. The value of the expression itself, paired with the label for the default statement is placed at the end of the table at run time. A simple loop generated by the compiler compares the value of the expression with each value in the table, being assured that if no other match is found, the last (default) entry is sure to match.

If the number of values exceeds 10 or so, it is more efficient to construct a hash table for the values, with the labels of the various statements as entries.

If no entry for the value possessed by the switch expression is found, a jump to the default statement is generated.

There is a common special case that can be implemented even more efficiently than by an n-way branch. If the values all lie in some small range, say min to max, and the number of different values is a reasonable fraction of max — min, then we can construct an array of max — min "buckets," where bucket j — min contains the label of the statement with value j; any bucket that would otherwise remain unfilled contains the default label.

To perform the switch, evaluate the expression to obtain the value j;check that it is in the range min to max and transfer indirectly to the table entry at offset j — min. For example, if the expression is of type character, a table of, say, and 128 entries (depending on the character set) may be created and transferred through with no range testing.