typestar

Jump tables in Assembly

Index into addresses instead of chaining compares.

; A jump table: index into addresses instead of chaining compares.
        global _start

        section .data
ops:    dq op_add2, op_double, op_square

        section .text
_start:
        mov rax, 6              ; input
        mov rcx, 2              ; choose op_square
        jmp [ops + rcx * 8]

op_add2:
        add rax, 2
        jmp done
op_double:
        add rax, rax
        jmp done
op_square:
        imul rax, rax           ; 36
done:
        mov rdi, rax
        mov rax, 60             ; exit code 36
        syscall

How it works

  1. dq op_add2, op_double, op_square stores three addresses.
  2. jmp [ops + rcx * 8] dispatches in one instruction.
  3. This is what a switch statement compiles into.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
423
Tokens
64
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 4 of 4 in Control flow, step 14 of 31 in Language basics.

← Previous Next →