DYSTOPIANPIXEL

Comparing with CP

Compare values without changing A.

Next Asset Lab concept artwork showing sprite patterns, palette colours and animation frames
Next Asset Lab concept artwork · Begin with Odin Dev.2k and the foundations of Z80 assembly.
TUTORIAL 2 / PART 04

CP: comparing without changing A

The instruction CP means compare. It works much like subtracting a value from A for the purpose of updating flags, but leaves the value in A unchanged. This is very useful when a value is needed after the decision.

Imagine A contains $12 and we execute CP $12. The conceptual subtraction $12 − $12 produces zero. Z becomes set; therefore the two values are equal. If instead we execute CP $20 with A still $12, a borrow is required; C becomes set. A remains $12 in either case.

$12cp $12SetClearA equals $12
$12cp $20ClearSetA is below $20
$20cp $12ClearClearA is above $12

After CP n, the useful unsigned interpretations are: Z means equality; C means A is less than n; NC means A is greater than or equal to n. Do not confuse an instruction’s textual order: cp $20 compares A against $20, not the other way round.

Important distinction: the instruction CP doesn’t create a Boolean variable containing TRUE or FALSE. It adjusts bits in F, which the following branch instruction can consult.

One pair of bytes — opposite unsigned and signed answers

The actual bytes do not change when you say “signed” or “unsigned”. Only their interpretation changes. This is why comparing $80 with $7F is a revealing example. The comparison instruction performs A minus the operand for flags; it does not alter A.

A=$80; CP $7F128 is above 127−128 is below +127C clear; P/V set
A=$7F; CP $80127 is below 128+127 is above −128C set; P/V set

In the first row, Carry is clear, which correctly answers the unsigned question “Is 128 below 127?” with “No”. But as signed numbers, −128 is below +127: the correct signed answer is the opposite. P/V is set because the conceptual signed subtraction cannot be represented within the signed eight-bit range.

For the reverse comparison, Carry is set because unsigned 127 is below unsigned 128; that does not mean signed +127 is below signed −128. Notice that S alone is not a reliable signed “less than” test whenever overflow occurs. More advanced signed conditions take overflow into account; we are deliberately not hiding a complicated expression inside this first exercise.

; Try one version at a time in Odin.
start:
    ld a,$80
    cp $7f
    ld hl,$6000
    ret

; Then change just these two instructions:
;   ld a,$7f
;   cp $80

Both versions leave A unchanged by CP. Use the flags displayed by Odin after R to verify Carry and P/V. The downloadable T02SGN.ASM contains the first version; edit its two constants for the reverse test.