Z80 assembly: Lookup and jump tables
Use an index to select a word from a table, then jump to that address.
A lookup table stores values in order. A jump table stores 16-bit addresses. Each address uses two bytes, low byte first. The program doubles the choice number to find its two-byte entry, loads that address into HL, then jumps there.
JP (HL) takes 4 T-states. It copies HL into PC. ADD HL,DE takes 11 T-states. The table lookup uses two memory reads.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
A contains choice 1. The code multiplies it by 2 to select the second address in the table at 0112h. That entry points to 0110h.
Registers and table bytes
Flags
DE holds the byte offset. HL first points to the table entry, then holds the selected target address. JP (HL) jumps to that address. This page ignores undocumented X and Y bits.
Jump table at 0112h
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
Branches or a table?
| Approach | Useful when | Memory access |
|---|---|---|
| Several conditional JP instructions | There are only a few choices | Fetches branch instructions |
| Jump table + JP (HL) | Many choices map to many targets | Reads one 16-bit address |
| Lookup table | Choice maps to a value, not code | Reads one or more data bytes |
Check that the choice is in range before reading a table. An invalid index can jump to an unrelated address.
The two table entries point to HALT instructions in this example. A real program would point to different code handlers.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads the table address and selected index. |
| ADD | Add | Doubles A, then adds the byte offset to HL. |
| EX | Exchange | Moves the loaded table address from DE into HL. |
| JP | Jump | Sets PC to the address in HL. |
| DB | Define Byte | Assembler directive. Stores each address as low byte then high byte. |
| HALT | Halt | Stops at the selected table entry. |