Z80 assembly: Lookup and jump tables

Use an index to select a word from a table, then jump to that address.

ADD HL,DE · JP (HL)

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.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

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

#AddressInstructionResultT-states

Branches or a table?

ApproachUseful whenMemory access
Several conditional JP instructionsThere are only a few choicesFetches branch instructions
Jump table + JP (HL)Many choices map to many targetsReads one 16-bit address
Lookup tableChoice maps to a value, not codeReads 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
NameStands forMeaning here
LDLoadLoads the table address and selected index.
ADDAddDoubles A, then adds the byte offset to HL.
EXExchangeMoves the loaded table address from DE into HL.
JPJumpSets PC to the address in HL.
DBDefine ByteAssembler directive. Stores each address as low byte then high byte.
HALTHaltStops at the selected table entry.