CPY Instruction (Compare Index Register Y and Memory)
Compares index register Y with memory and returns the result to the status flags.
CPY Overloads
| Opcode | Syntax | Addressing mode | Bytes | Cycles | Notes |
|---|---|---|---|---|---|
| C0 | CPY #const | Imm. | 2/ 3 | 2 | 1, 3 |
| C4 | CPY dp | DP. | 2 | 3 | 1, 2 |
| CC | CPY abs | Abs. | 3 | 4 | 1 |
Notes
- Add 1 cycle when the index flag is clear.
- Add 1 cycle when the direct page start address is not on a page boundary.
- 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