Switch Lowering in GCC
- ID
- 41794
- Status
- summarized
- Published
- 31 Oct 2026, 4:02 PM
- Fetched
- 02 Nov 2026, 2:40 AM
- Provider
- Hacker News
- Category
- dev-community
- Original URL
- https://xoranth.net/gcc-switch/
- Source URL
- https://hnrss.org/best
Summary
- Score
- 5.5
- Created
- 02 Nov 2026, 2:41 AM
- Tags
- Audience
- developers
What happened
A deep dive into how GCC lowers switch statements at -O3: small dense switches become jump tables, and GCC normalises offsets automatically (cases 97–101 compile to `lea eax, [rdi-97]` before the indirect jump). Through experimentation the author pins GCC's density heuristic at roughly eight jump-table entries per case label — so a switch with cases at 0, 7, 14, 21 and 34 still gets a jump table with padding slots, while a sparser one does not. The post notes all the optimisations discussed except bitset lowering also apply to clang.
Why it matters
The shape of your switch cases, not just their count, decides whether GCC emits an indirect jump or a compare chain — and sparse case values can produce padded jump tables with many dead slots. If you're hand-tuning a hot dispatch path, either cluster your case values densely or check the actual assembly (the post's `cmp eax, 34 / ja` + table pattern is the tell), rather than assuming a switch is free.
Discussion angle
Pull up the switch in your own hot path and compile it at -O3 — does GCC give you a jump table or a compare chain, and would renumbering your case values (or switching to a function-pointer array) actually change the generated code?