Z80 assembly: Comparing and jumping
Compare bytes in a table. A conditional jump changes the next address when a flag matches.
CP compares A with a value by subtracting it for the flags. A stays unchanged. JP jumps to a full 16-bit address. JR jumps by a signed 8-bit offset. Both can test conditions such as Z, NZ, C and NC.
CP A,n takes 7 T-states. JP nn takes 10. JR takes 12 when taken and 7 when not taken. DJNZ takes 13 when taken and 8 when B reaches zero.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The program checks three bytes at 0114h–0116h for 2Ah. The matching byte is at 0115h. Step through CP, JP Z and the loop branches.
Registers, flags and table bytes
Flags
CP changes flags as subtraction would, but keeps A unchanged. Z is set when the compared values are equal. This page ignores undocumented X and Y bits.
Table data at 0114h
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
Compare the loop forms
| Method | Bytes | Time | Flags |
|---|---|---|---|
| DJNZ loop | 2 bytes | 13 T taken; 8 T final | unchanged |
| DEC B + JR NZ | 3 bytes | 16 T taken; 11 T final | DEC changes flags |
The comparison is for loop control only. The search also uses CP and branches to the match or finish address.
The program scans a fixed three-byte table. It does not read input or use interrupts. JP and JR use the documented Z80 flag conditions.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads the table address and loop count. |
| CP | Compare | Subtracts for flags without changing A. |
| JP | Jump | Loads a full address into PC when its condition is true. |
| JR | Jump Relative | Adds a signed offset to the next instruction address. |
| DJNZ | Decrement B and Jump if Not Zero | Counts table entries. |
| DB | Define Byte | Assembler directive. Places table bytes in memory. |
| HALT | Halt | Stops this lesson’s CPU. |