LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

What is a jump table and why do compilers use it for switch statements?

A jump table is an array of code addresses indexed by the switch value, letting the CPU jump straight to the right case in constant time instead of testing cases one by one.

The switch value indexes a jtab array of code addresses, then an indirect jump goes to the selected case block in constant time.

* Jump table: one array lookup plus one indirect jump gives O(1) dispatch. *

Instead of a chain of comparisons (if x==1 … else if x==2 …, which is O(n)), the compiler builds a small table where slot i holds the address of the code for case i. Selecting a case is then one array lookup plus one indirect jump — O(1), regardless of how many cases there are:

target = jtab[x];   // look up the address for this case
goto *target;       // indirect jump to it

Setup assembly:

    cmpq  $6, %rdi          # is x outside 0..6 ?
    ja    .L8               # if above (unsigned >) goto default
    jmp   *.L4(,%rdi,8)     # goto *jtab[x]  (8 = bytes per address)

The table itself, in .rodata:

.section .rodata
.align 8
.L4:
    .quad .L8   # x = 0 -> default (hole)
    .quad .L3   # x = 1 -> case 1
    .quad .L5   # x = 2 -> case 2
    .quad .L9   # x = 3 -> case 3
    .quad .L8   # x = 4 -> default (hole)
    .quad .L7   # x = 5 -> case 5/6
    .quad .L7   # x = 6 -> case 5/6

Note the cmpq $6 / ja guard: because ja is an unsigned comparison, both negative x and x > 6 exceed 6 when read as unsigned, so a single check sends every out-of-range value to default.

Go deeper:

From Quiz: REVE1 / Translation of C to Assembly | Updated: Jul 10, 2026