ADD and CMP in 8086 Assembly: Arithmetic, Comparison and Flags

ADD and CMP are the pair that turns the 8086 from a copying machine into a machine that can make decisions. ADD changes a value and records what happened in the flags. CMP does the same subtraction as SUB, but throws the result away and keeps only the flags, so a conditional jump can act on the comparison.

ADD: syntax and effect on flags

ADD destination, source   ; destination = destination + source

ADD affects all six arithmetic flags: overflow (OF), sign (SF), zero (ZF), auxiliary carry (AF), parity (PF) and carry (CF). If the addition overflows the destination size, the extra bit lands in CF; if a signed result overflows, OF is set. A quick way to remember it: ADD tells the truth about the result in every flag at once.

CMP: compare without storing

CMP AX, BX   ; computes AX - BX, keeps only the flags

After CMP, ZF tells you whether the operands were equal, CF tells you about an unsigned borrow, and SF and OF together tell you about a signed comparison. That is why two families of conditional jumps exist: JA, JB, JAE and JBE read the result as unsigned, while JG, JL, JGE and JLE read it as signed. Using the wrong family is one of the most common bugs in student programs, because the same two numbers can be “greater” unsigned and “less” signed.

INC and DEC: the exception to remember

INC adds one and DEC subtracts one, and both affect OF, SF, ZF, AF and PF, but neither affects CF. That is deliberate: a loop counter incremented with INC does not destroy a carry flag that surrounding code is using. If you need CF updated, use ADD or SUB with 1 instead.

Worked example: compare two numbers and print the larger

This .COM example compares two values, prints a character for the larger one, and exits through DOS. It uses only instructions covered in this post and in the MOV post:

ORG 100h

MOV AX, 25
MOV BX, 40
CMP AX, BX
JAE ax_is_bigger     ; unsigned: AX >= BX
; BX is bigger here.
MOV DL, 'B'
JMP print_it
ax_is_bigger:
MOV DL, 'A'
print_it:
MOV AH, 02h          ; INT 21h, AH=02h: write character in DL
INT 21h
MOV AX, 4C00h        ; INT 21h, AH=4Ch: exit to DOS
INT 21h
RET

Change the two starting values and watch the printed letter change. Then change JAE to JGE and try values that cross the signed boundary, such as comparing a value with its high bit set against a small positive value, to see the signed and unsigned families disagree.

Quick reference: which instructions touch which flags

Instruction OF SF ZF AF PF CF
MOV no no no no no no
ADD, SUB, CMP yes yes yes yes yes yes
INC, DEC yes yes yes yes yes no

The rule of thumb: if an instruction computes a result, it usually reports on it; MOV is the notable exception, and INC and DEC are the partial exception.

Further reading

Similar Posts