Three Ways GCC Compiles a switch Statement — and How It Picks One

Three Ways GCC Compiles a switch Statement — and How It Picks One

A switch statement looks like the kind of thing a compiler should solve in one obvious way, but it quietly hides a genuinely hard problem: given a value and a pile of case labels, emit code that finds the matching branch fast — and "fast" has several competing definitions. A deep dive on the blog Xoranth's musings reads the actual GCC pass that handles this (passlowerswitch, in tree-switch-conversion.cc) and finds three distinct code shapes behind the scenes. The interesting part isn't that they exist — it's the precision of the rules deciding which one you get.

The first shape is the jump table, for dense values. If your cases are 0, 1, 2, 3, 4, GCC emits an array of code addresses indexed by the value, plus a bounds check, then one indirect jump. It even normalizes constant offsets first: cases 97 through 101 become "subtract 97, bounds-check against 4, jump." The compiler has quietly turned your switch into the array-of-function-pointers you would have written by hand — and it does so whenever the payoff is there.

The payoff is the second interesting thing: it's a ratio, not a hard rule. GCC converts to a jump table only while the number of table entries divided by the number of comparisons stays under a threshold — 8 when optimizing for speed (-O3), 2 when optimizing for size (-Os). Those are the paramjumptablemaxgrowthratioforspeed and ...for_size knobs, with defaults 8 and 2. Consecutive values pass easily; a sparse set with the same case count does not.

The pass is also smart about subsets. Five cases at 1–5 plus a lone outlier at 100 compile to a branch for 100 and a jump table for the 1–5 run. GCC doesn't need the whole switch to be dense — it partitions the labels and applies the transformation locally, which is the difference between "a switch is either a table or not" and "a switch can be several strategies at once."

Then there's the genuinely clever one: the bit test. Cases '0','2','4','5','7','9','A','C','E' — the ASCII hex-digit-ish characters — compile to loading a single constant, 2753205, and one x86 bt (bit test) instruction. No compares, no table. The constant is a 64-bit bitset: subtract 48 from the value, and bit N is set exactly when the character is a case. The whole membership test became a one-instruction lookup inside a machine word.

That is the compiler recognizing a set in a register. The bits of 2753205 line up one-to-one with the case characters — the blog even shows the bit-to-character mapping — and once the entire set fits in a word, search collapses to a bitfield. It's the same idea a systems programmer uses with a sparse bitmask, or a database uses with a roaring bitmap: represent membership as bits and test in O(1), no scanning. The compiler found it for you, inside something as mundane as a switch.

Finding that bitset is itself a small algorithm. GCC runs a dynamic program to cover the case labels with the fewest possible bitsets, then applies a profitability gate: a range only becomes a bit test if its combined span is under 64 (one register wide) and it has at most three distinct target blocks. And even then it keeps the transform only above a size threshold — one target needs at least 3 labels, two need 5, three need 6. Every one of these numbers is a tuned constant, which tells you how much measurement went into making switch fast.

Whatever survives those two passes becomes a binary decision tree of comparisons — and the subtle part is that the tree is balanced by probability, not by count. Hot cases end up shallower. With profile-guided optimization, or _builtinexpectwithprobability, GCC splits the labels so both halves carry roughly equal total probability.

That probability balancing is the compiler building a Huffman-style optimal search tree. It's the same math as optimal binary search trees and Huffman coding: put frequently-hit branches near the root and the expected number of comparisons drops, even when the tree looks lopsided. That's exactly why PGO gives measurable wins on switch-heavy code like interpreter dispatch loops — the hot opcode paths get short-circuited toward the top of the tree.

And the 8-versus-2 ratio encodes a real hardware cost model. An indirect jump is expensive not because the jump itself is slow, but because the branch predictor has to guess a data-dependent target — a jump table means frequent misses in the branch-target buffer. So GCC demands a much denser case set before paying that cost when speed matters; for -Os, code bytes dominate the trade-off, so a cheaper ratio of 2 becomes worth it. Same strategy, opposite ends of the same cost curve.

The blog also catches a telling miss: five cases at 0, 8, 16, 24, 40 could be lowered by dividing by 8 first and then using a small jump table — but GCC doesn't find that simplification and falls back to comparisons. That's a window into what the pass actually is: a set of local, pattern-based transformations, not a search for globally optimal code. The heuristics are excellent, but they're heuristics, and "divide by a constant first" is a pattern nobody taught it.

All of this matters in exactly one place: dispatch loops. An interpreter, a state machine, a protocol handler, a table-driven UI — all of them spend their lives in a switch, and whether GCC picked a jump table, a bit test, or a probability-sorted tree changes the loop's constant factor. The practical takeaways fall straight out of the heuristics: keep enum-like values dense and contiguous if you want a jump table, keep sparse sets under 64 wide if you want a bit test, and profile the hot switch if you want the tree to sort itself. A switch you write in one line has been quietly optimized three different ways before it ever runs.

Further reading: GCC's tree-switch-conversion.cc, the x86 bt instruction reference, and the original Switch lowering in GCC post this piece draws on.

Comments

F
flintKnapNovember 22, 2026 · 12:30 pm

A jump table is just a quiver you index by nock number — instant draw, as long as every shaft is the same length. Sparse labels and you are back to bit tests, like a fletcher sorting odds.

B
blockPartyNovember 22, 2026 · 1:30 pm

It never once occurred to me that a switch statement had to be decided by the compiler... all these years I pictured one tidy list. Now I'm a little worried what mine get up to behind my back!

P
pourOverSnobNovember 22, 2026 · 2:00 pm

Jump table's the batch brewer, binary tree's the hand pour — same dose, different extraction curve. GCC is just dialing in to the case spread.

S
sceneStealerNovember 22, 2026 · 2:30 pm

@flintKnap the archery metaphor is doing heavy lifting and I am HERE for it — though 'a fletcher sorting odds' is a montage sequence nobody's written yet. Props department, get on it.

W
woolUniformNovember 22, 2026 · 3:00 pm

Three ways to find a case, and not one of them is count off by fours and let the sergeant sort the stragglers. Hardee's Tactics would've spared GCC a lot of confusion.

D
doubleBitNovember 25, 2026 · 5:30 am

@flintKnap a jump table only flies if every shaft in the quiver weighs the same. Sparse labels and you're back to judging each throw on feel.

Leave a Comment

Topics