6.4 Compare, Branch, and Loop Instructions
So far execution has moved straight to the next instruction. A control-transfer instruction changes IP so the CPU can choose a path or repeat work. Conditional transfers do not guess from source code types; they read flags produced by an earlier operation.
CMP subtracts for flags without storing the result
CMP left,right performs the same internal subtraction as SUB left,right, but discards the numeric result. The operands remain unchanged; CF, PF, AF, ZF, SF, and OF describe left−right.
For equality, only ZF matters:
JEorJZjumps when ZF=1.
JNEorJNZjumps when ZF=0.
Ordering needs the correct numeric interpretation:
- Unsigned jumps use CF and ZF:
JA,JAE,JB, andJBE.
- Signed jumps combine SF, OF, and sometimes ZF:
JG,JGE,JL, andJLE.
The same bits can reverse an ordering. F0H is unsigned 240 but signed −16; 10H is 16 in both interpretations. After CMP F0H,10H, unsigned JA is taken, while signed JL is also taken. Neither contradicts the other because the program asked two different questions.
LOOP uses CX as an implicit counter
LOOP target performs two actions:
1. Decrement CX without changing arithmetic flags.
2. Jump to target if the new CX is not zero.
The loop body normally appears before LOOP, so a starting CX of 1 executes the body once. A starting CX of 0 is dangerous: LOOP first changes it to FFFFH, causing 65,536 body executions before it eventually reaches zero.
JCXZ target jumps when CX is already zero and does not modify CX. Use it before the body when zero is a valid input:
JCXZ finished
again:
; loop body
LOOP again
finished:A programmer can write DEC CX followed by JNZ, but DEC changes status flags. LOOP changes CX and IP without changing them. This matters if the loop body calculated flags that code after the loop still needs. It also makes LOOP’s counter use implicit: the instruction text does not name CX.
Branches choose among instruction addresses, while loops revisit them. Section 6.5 applies both repetition and implicit registers to blocks of bytes using the 8086 string instructions.