How GCC Turns a C Switch into Machine Code


A switch statement describes a mapping from values to actions. It does not tell the processor how to find the right action. That missing step is a compiler design problem: should the generated code compare values one by one, index a table of destinations, or test membership in a set of bits?

The answer depends on the shape of the cases. Five consecutive numbers present a different problem from five numbers spread across a large range. Several labels that lead to the same block change the calculation again. GCC can even combine strategies inside one switch.

This walkthrough builds on Xoranth’s investigation of GCC switch lowering and GCC’s documented optimization parameters. The article examined a particular GCC version and x86-64 output with -O3; exact thresholds and assembly can change with compiler version, target, and flags. The decision principles are more durable than a particular listing.

The switch is a dispatch problem

Consider a function that chooses one of five handlers:

int dispatch(int key, int value) {
    switch (key) {
    case 0: return handle_0(value);
    case 1: return handle_1(value);
    case 2: return handle_2(value);
    case 3: return handle_3(value);
    case 4: return handle_4(value);
    default: return 0;
    }
}

The compiler must preserve the source behavior, including the default result for values outside 0..4. But it can choose any equivalent route to a handler. In this dense example, the useful route is a bounds check followed by an indexed jump table. Once the key is known to be in range, the machine loads the destination associated with that key and jumps there.

In broad terms, the generated operation is:

if key > 4: go to default
go to table[key]

The table has five destination entries. If the labels were 97..101, GCC could subtract 97 before the same range check and index. A constant offset does not make a compact range fundamentally sparse.

One switch input can be lowered through an indexed jump table, a bit membership test, or a comparison tree, depending on the shape of its cases.
GCC chooses a dispatch structure from the case layout; a switch need not use one strategy for every case.

Density makes a jump table attractive

A jump table offers a short dispatch path, but it needs an entry for every value between its minimum and maximum, including gaps. Empty entries point to the default destination. A switch with cases 0, 7, 14, 21, 34 therefore needs 35 slots if implemented as one table. A wider range can make a table too large for the comparison work it saves.

Xoranth’s experiments found that a similar set ending at 40 was lowered as a comparison tree instead. The interesting quantity was not simply the number of labels. It was the range width relative to the estimated number of comparisons. GCC exposes separate growth controls for speed and size through jump-table-max-growth-ratio-for-speed and jump-table-max-growth-ratio-for-size; it also exposes case-values-threshold, a minimum case count for table use. Those are tuning inputs, not a promise that every switch with a given density will compile identically.

An outlier demonstrates why the choice is local. With cases 1..5 plus 100, GCC can use a table for the compact run and a separate comparison for 100. Forcing all six cases into a 100-entry table would spend space on a long empty region. Forcing all six through comparisons would discard the cheap indexed dispatch for the dense part.

The key lesson is that a switch can become a tree whose leaves include tables. “Does GCC use a jump table?” is often the wrong yes-or-no question. Ask which subsets are dense enough to merit one.

Shared destinations change the cost

Now imagine four adjacent labels all call the same handler:

case 42:
case 43:
case 44:
case 45:
    return handle_group(value);

These are four source labels but one destination interval. The compiler can check whether key lies within 42..45 using a pair of boundary comparisons. A table entry for each of the four numbers buys less than it did when each number led to a distinct handler.

In Xoranth’s larger example, five groups of four labels span 0..87. A naive count says 20 labels over 88 possible values and suggests that a table may be worthwhile. But each group is contiguous and shares a destination. GCC represents those ranges as clusters, then estimates comparison cost using the clusters. The resulting comparison tree can be cheaper than an 88-slot table.

This distinction matters when reading generated assembly. Source-level case count is not the unit of work the optimizer necessarily sees. Earlier compiler passes may already have folded neighboring labels into ranges.

A bitset can represent membership

Another shape appears when several nonadjacent labels share one destination. Suppose a switch accepts the characters 0, 2, 4, 5, 7, 9, A, C, and E, and returns the same result for each. A chain of equality checks is possible, but a compact bit mask can answer the membership question at once.

Subtract the lowest character code, 48 for 0, to get a bit index. Set one bit in a machine word for each accepted value. The result in the original example is the integer 2753205. For an input character, a bounds check keeps the index inside the representable span, and a bit-test instruction asks whether the corresponding bit is set. If it is, execution goes to the shared handler; otherwise, it follows the default path.

index = character - '0'
if index is outside the mask span: default
if mask has bit[index]: shared handler
else: default

This is a compact representation of a set, not a table of different destinations. A single bit can say “yes, this value belongs,” but it cannot by itself say which of many unrelated handlers to call. GCC’s cluster logic can use multiple bit tests when a small number of destinations are involved; the precise profitability rules remain target and version dependent.

A character is normalized by subtracting the lowest accepted code, checked against the mask width, then used to select one bit in a membership mask.
Bit testing trades a run of equality checks for a range check and one membership lookup.

The fallback is a comparison tree

When no useful compact cluster emerges, GCC can lower the remaining cases into a decision tree. A tree first compares against a pivot, then searches the lower or higher portion of the case range. This avoids a long linear sequence for many sparse labels.

The tree is not necessarily balanced only by the number of labels. GCC also tracks probabilities for case edges. Profile-guided optimization can supply observed frequencies, and source hints can influence probabilities. A hot case can be placed where the expected path to it is short, even if that creates an uneven tree by label count. This is a performance trade-off: minimizing the average dispatch work may matter more than making every path the same length.

The comparison tree also joins the earlier strategies together. GCC’s lowering work first considers bit-test clusters, then jump-table clusters for the cases left over, and finally expands the remaining simple cases as comparisons. The resulting structure can contain a comparison that selects a dense jump-table region, another branch for an outlier, and a bit test for a group sharing a destination. The compiler is assembling a dispatch plan, not applying a single global template.

Why the optimizer uses dynamic programming

Once cases are sorted into clusters, the compiler still has to decide where to split them. For example, a run of ten cases might be one wide table, two small tables with comparisons between them, or a set of simple cases. Picking the best local decision at each label could miss a better grouping farther along.

The lowering routines described in the original investigation use dynamic programming to consider prefixes of the ordered clusters. For each prefix, they evaluate possible starting points for the final group and keep the best score seen so far. Bit-test grouping asks whether a span fits the available word and a small enough set of destinations. Jump-table grouping weighs the covered numeric range against comparison cost, a minimum useful table size, and the current speed-versus-size goal. Splits that are too small to justify a table count against the candidate.

This does not mean GCC solves a perfect hardware-performance model. Its scores are heuristics. Real speed also depends on branch prediction, instruction cache pressure, memory access, and the processor. The dynamic program chooses among the compiler’s candidate representations using its cost rules; benchmarking is still the way to know whether a particular generated form is faster in a real workload.

Reading your own switch output

If a switch is on a measured hot path, inspect the generated assembly for the compiler and target you ship. Compile a small representative function with optimization enabled and look for three signatures:

  • Jump table: a range check followed by an indirect jump through an indexed table.
  • Bit test: a normalized index, a mask constant or loaded mask, and a bit-test or equivalent shift-and-test sequence.
  • Comparison tree: ordered comparisons and branches, sometimes with a table or bit-test leaf.

Try the build’s actual -O setting, architecture, and profile data. -Os can prefer a smaller tree where -O3 prefers a table. Changing the case values, merging destinations, or adding one distant outlier can alter the shape. Do not rewrite source into hand-built tables solely because the syntax looks expensive: first check what the compiler already emitted and measure the call site.

The larger point is that a switch is a declarative dispatch map. Its performance comes from the map’s structure and the compiler’s cost model. Dense distinct cases favor indexed destinations; sparse shared outcomes may favor bit masks; wide sparse ranges favor comparisons; mixed maps can use all three.

Sources

100%