1min.

1MIN · PROGRAMMING LANGUAGES

A switch statement can become a table or a comparison tree

Xoranth walks through how GCC translates switch statements into machine code. Closely spaced case values can become a jump table, while sparse values can lead to comparison trees or mixed strategies. The examples connect source code to generated assembly, showing why the number and spacing of cases matter when reasoning about the resulting control flow.

Xoranth · Jan 14, 2024

Why it matters

Inspect the compiled code before drawing performance conclusions from the shape of a source-level switch.

More context

This January 2024 tutorial presents small examples, generally compiled with optimization enabled, and explains the resulting instructions. It is useful practice for reading assembly and understanding compiler choices. Keep the compiler version, target and flags visible when repeating the exploration.

Keep in mind

The examples explain lowering strategies rather than proving one source style is always faster. Compiler heuristics and generated instructions can change across versions and architectures.

Original read

More engineering ideas, one minute at a time.

Explore more stories