CPY Instruction (Compare Index Register Y and Memory)

Compares index register Y with memory and returns the result to the status flags.

CPY Overloads

OpcodeSyntaxAddressing modeBytesCyclesNotes
C0CPY #constImm.2/ 321, 3
C4CPY dpDP.231, 2
CCCPY absAbs.341

Notes

  1. Add 1 cycle when the index flag is clear.
  2. Add 1 cycle when the direct page start address is not on a page boundary.
  3. 3 bytes when the index flag is clear; 2 bytes when the index flag is set.

Flag changes

n-----zc

n: Set to the MSB of the comparison result.
z: Set when the comparison result is 0.
c: Set when no unsigned borrow occurs in the comparison (this is equivalent to an arithmetic overflow occurring in the internal operation).

Explanation

The CPY instruction compares the Y register with the value specified by the operand, according to the addressing mode specified by the opcode, and returns the result to the status flags.
The comparison is done by subtraction: the memory value is subtracted from the Y register. This instruction does not change the Y register or memory.

If the result is 0, that is, if the Y register and the memory value are equal, the Z flag is set. If no borrow occurs, that is, if the Y register value is greater than or equal to the memory value, the carry flag is set.

Examples

Reading up to the end of a string

    ; process the string pointed to by $00-$02 up to the terminating $00 (A is 8-bit, Y is 16-bit)
    LDY.w #$0000
.loop
    LDA [$00],Y
    BEQ .end        ; reached the terminator
    ; ... process one character ...
    INY
    CPY.w #$0100
    BCC .loop       ; cut off at 256 characters just in case
.end

See also

SBC Instruction
CMP Instruction
CPX Instruction