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

OpcodeSyntaxAddressing modeBytesCyclesNotes
C9CMP #const
CPA #const
Imm.2/ 321, 4
C5CMP dpDP.231, 2
D2CMP (dp)DP. Ind251, 2
C7CMP [dp]DP. Ind long261, 2
D5CMP dp, XDP. Idx X241, 2
C1CMP (dp, X)DP. Idx Ind X261, 2
D1CMP (dp), YDP. Ind Idx Y251, 2, 3
D7CMP [dp], YDP. Ind long Idx Y261, 2
CDCMP absAbs.341
DDCMP abs, XAbs. Idx X341, 3
D9CMP abs, YAbs. Idx Y341, 3
CFCMP longAbs. long451
DFCMP long, XAbs. long Idx X451
C3CMP sp, SSR.241
D3CMP (sp, S), YSR. Ind Idx Y271

Notes

  1. Add 1 cycle when the memory mode flag is clear.
  2. Add 1 cycle when the direct page start address is not on a page boundary.
  3. Add 1 cycle when adding the index crosses a page boundary, or when the index registers are 16-bit.
  4. 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.

See also

SBC Instruction
CPX Instruction
CPY Instruction