CMP
CMP (short for "CoMPare") is the mnemonic for a machine language instruction which compares the contents of the accumulator against that of the specified operand by subtracting operand from accumulator value, and setting the negative and carry flags according to the result. Unlike SBC, the result of the subtraction is discarded rather than stored back into the accumulator, which is thus unaffected by the CMP operation.
Usage[edit | edit source]
- Main article: Comparisons in machine language
To compare integers in machine language, first use a comparison instruction such as CMP, CPX or CPY to compare the numbers, then "test" the result using a conditional branch instruction that acts on the carry or negative flags, i.e. BCC, BCS, BMI, or BPL:
- If the compared values are unsigned integers, use BCC to branch if the contents of the accumulator is less than that of the memory address, and BCS to branch if the accumulator holds a number equal to or larger than that in memory.
- If the compared values are signed integers, use BMI to branch if the contents of the accumulator is less than that of the memory address, and BPL to branch if the accumulator holds a number equal to or larger than that in memory.
Addressing modes[edit | edit source]
Opcode | Addressing mode |
Assembler format |
Length in bytes |
Number of cycles | |
Dec | Hex | ||||
201 | C9 | Immediate | CMP #nn | 2 | 2 |
205 | CD | Absolute | CMP nnnn | 3 | 4 |
221 | DD | Absolute,X | CMP nnnn,X | 3 | 4* |
217 | D9 | Absolute,Y | CMP nnnn,Y | 3 | 4* |
197 | C5 | Zeropage | CMP nn | 2 | 3 |
213 | D5 | Zeropage,X | CMP nn,X | 2 | 4 |
193 | C1 | Indexed-indirect | CMP (nn,X) | 2 | 6 |
209 | D1 | Indirect-indexed | CMP (nn),Y | 2 | 5* |
CMP supports eight different addressing modes, as shown in the table at right.
In the assembler formats listed, nn represents a single-byte (8-bit) figure, and nnnn is a two-byte (16-bit) address.
With some addressing forms (marked with an asterisk, *, in the "Number of cycles" column) the execution time for CMP depends on the circumstances: In cases where the indexing requires the CPU to "reach across" a page boundary from the base address, the execution time is 1 cycle longer than listed here.
CPU flags[edit | edit source]
CMP affects 3 of the CPU's status flags:
- The negative status flag is set if the result is negative, i.e. has it's most significant bit set.
- The zero flag is set if the result is zero, or cleared if it is non-zero.
- The carry flag is set or cleared depending on the result.