Switch Statements

Any C Compiler requires efficient translation of switch statements. The Compiler applies different strategies, that is, branch trees, jump tables, and a mixed strategy, depending on the case label values and their numbers. The following table describes how the Compiler implements these strategies.

Table 1. Switch Implementations
Method Description
Branch Sequence For small switches with scattered case label values, the Compiler generates an if ... elsif ... elsif ... else ... sequence if the Compiler switch -Os is active.
Branch Tree For small switches with scattered case label values, the Compiler generates a branch tree. This is equivalent to unrolling a binary search loop of a sorted jump table and therefore is very fast. However, there is a point at which this method is not feasible simply because it uses too much memory.
Jump Table When the branch tree method is not feasible, the Compiler creates a table plus a call of a switch processor. There are two different switch processors. The Compiler uses a direct jump table when there are a lot of labels with more or less consecutive values, and a binary search table when the label values are scattered.
Mixed Strategy In some cases switches may have clusters of consecutive label values separated by other labels with scattered values. In this case, the Compiler applies a mixed strategy, generating branch trees or search tables for the scattered labels and direct jump tables for the clusters.