CMP Instruction (Compare Accumulator and Memory)
Compares the accumulator with memory and returns the result to the status flags.
CPA is an alias of CMP.
CMP Overloads
| Opcode | Syntax | Addressing mode | Bytes | Cycles | Notes |
|---|---|---|---|---|---|
| C9 | CMP #const CPA #const | Imm. | 2/ 3 | 2 | 1, 4 |
| C5 | CMP dp | DP. | 2 | 3 | 1, 2 |
| D2 | CMP (dp) | DP. Ind | 2 | 5 | 1, 2 |
| C7 | CMP [dp] | DP. Ind long | 2 | 6 | 1, 2 |
| D5 | CMP dp, X | DP. Idx X | 2 | 4 | 1, 2 |
| C1 | CMP (dp, X) | DP. Idx Ind X | 2 | 6 | 1, 2 |
| D1 | CMP (dp), Y | DP. Ind Idx Y | 2 | 5 | 1, 2, 3 |
| D7 | CMP [dp], Y | DP. Ind long Idx Y | 2 | 6 | 1, 2 |
| CD | CMP abs | Abs. | 3 | 4 | 1 |
| DD | CMP abs, X | Abs. Idx X | 3 | 4 | 1, 3 |
| D9 | CMP abs, Y | Abs. Idx Y | 3 | 4 | 1, 3 |
| CF | CMP long | Abs. long | 4 | 5 | 1 |
| DF | CMP long, X | Abs. long Idx X | 4 | 5 | 1 |
| C3 | CMP sp, S | SR. | 2 | 4 | 1 |
| D3 | CMP (sp, S), Y | SR. Ind Idx Y | 2 | 7 | 1 |
Notes
- Add 1 cycle when the memory mode flag is clear.
- Add 1 cycle when the direct page start address is not on a page boundary.
- Add 1 cycle when adding the index crosses a page boundary, or when the index registers are 16-bit.
- 3 bytes when the memory mode flag is clear; 2 bytes when the memory mode 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 CMP instruction compares the accumulator 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 accumulator. This instruction does not change the accumulator or memory.
If the result is 0, that is, if the accumulator and the memory value are equal, the Z flag is set. If no borrow occurs, that is, if the accumulator value is greater than or equal to the memory value, the carry flag is set.
Examples
The CMP instruction is used to dispatch processing with branch instructions according to the result of the comparison. For unsigned values, greater/less is decided with BCC and BCS, which look at the carry flag.
Branching on greater/less
LDA $10
CMP.b #$40
BCC .less ; when A < $40
BEQ .equal ; when A = $40
; we get here when A > $40
Range check
; check whether A is in the range $20-$3F
CMP.b #$20
BCC .out ; less than $20
CMP.b #$40
BCS .out ; $40 or greater
; we get here when it is in range
To compare signed values, you need to decide using a combination of the negative flag and the overflow flag rather than the carry flag.