Chapter 7: Flow Control

Microprocessors
IP and sequential executionUnconditional jump (JMP)Single-flag jumps Comparing with CMPSigned / unsigned jumpsThe LOOP family Nested loopsExample programs
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

How jumps work

Direct program flow with JMP and labels; explain how IP changes and how the displacement (offset) is computed.

Conditional jumps

State which flag (ZF, CF, SF, OF, PF) each conditional jump tests and name its opposite.

Correct comparisons

After CMP, choose JA/JB for unsigned numbers and the JG/JL family for signed ones.

Loops

Write counted loops with LOOP, LOOPE/LOOPZ, LOOPNE/LOOPNZ and JCXZ; trace the example programs step by step.

Introduction

Program Flow Control

  • Normally the CPU executes instructions in memory order: after each instruction, IP (Instruction Pointer) advances by the instruction's length.
  • Flow control instructions load a new value into IP and move execution somewhere else.
  • This is how decisions (if/else) and loops (for/while) are built at the machine level.
Sequential (IP += length)Jump (IP ← target)mov ax, 5mov ax, 5mov bx, 2mov bx, 2jmp calcjmp calcback: jmp stopback: jmp stopcalc: add ax, bxcalc: add ax, bxjmp backjmp backstop: retstop: ret
Unconditional jumpJMP target: always jumps.
Conditional jumpsSingle-flag tests, plus signed and unsigned comparisons.
LoopsLOOP, LOOPE/LOOPZ, LOOPNE/LOOPNZ, JCXZ.

Unconditional Jump

JMP: Unconditional Jump

  • JMP target transfers control to another point in the program unconditionally; it does not change the flags.
  • It can jump both forward and backward.
  • A near jump reaches anywhere in the current code segment (64 KB = 65,536 bytes, offsets 0000h–FFFFh); only IP changes.
  • A far jump changes CS and IP together and moves to another segment.
  • If the target is close, the assembler can pick the 2-byte short form automatically.
FormCodeBytesRange
JMP SHORTEB rel82−128…+127
JMP NEARE9 rel163within segment
JMP FAREA ofs seg5CS:IP
JMP reg/memFF /42–4indirect
rel8 / rel16: the signed distance of the target from the instruction after the jump.

Unconditional Jump

Labels

  • To define a label, write its name followed by :: again:
  • It may contain letters, digits and characters such as _, but it cannot start with a digit.
  • It can stand on its own line or in front of an instruction: back: jmp stop
  • A label takes no memory; the assembler turns it into an address (offset).
  • Instruction and register names (mov, ax …) cannot be labels; each label is defined once.
0100hMOV CX, 30103hagain: DEC CX0104hJNZ againassembler: again = 0103ha label takes no bytes; it is an address

Valid

  • again:
  • next_char:
  • k1:  calc:

Invalid

  • 1start: starts with a digit
  • mov: instruction name
  • two words: contains a space

Unconditional Jump · Step through the code

Code Trace: Forward and Backward with JMP

The program starts at address 0100h (org 100h, a .COM program). IP = 0100h.

mov ax, 5 (3 bytes) executed: AX = 0005h, IP = 0103h.

mov bx, 2: BX = 0002h. Next is the jmp calc at 0106h.

jmp calc: IP ← calc = 010Ah. The back: line in between is skipped.

add ax, bx: AX = 5 + 2 = 0007h.

jmp back: a backward jump, IP ← 0108h.

back: jmp stop: forward again, IP ← 010Eh.

ret: IP ← 0000h, the program ends. Result AX = 0007h. Flow: 1 → 2 → 3 → calc → back → stop.

org    100h
mov    ax, 5          ; ax = 5
mov    bx, 2          ; bx = 2
jmp    calc           ; go to 'calc'
back:  jmp stop       ; go to 'stop'
calc:
add    ax, bx         ; ax = ax + bx
jmp    back           ; back to 'back'
stop:
ret                   ; return to the OS

Unconditional Jump

Computing the Displacement

addressmachine codeinstruction0100hB8 05 00mov ax, 50103hBB 02 00mov bx, 20106hEB 02jmp calc0108hEB 04back: jmp stop010Ah01 D8calc: add ax, bx010ChEB FAjmp back010EhC3stop: retjmp calc @ 0106h (2 bytes)next IP = 0108htarget calc = 010Ahrel8 = 010A − 0108 = +2code: EB 02

Forward jump: the distance is measured from the address after the jump → +2.

addressmachine codeinstruction0100hB8 05 00mov ax, 50103hBB 02 00mov bx, 20106hEB 02jmp calc0108hEB 04back: jmp stop010Ah01 D8calc: add ax, bx010ChEB FAjmp back010EhC3stop: retjmp stop @ 0108hnext IP = 010Ahtarget stop = 010Ehrel8 = 010E − 010A = +4code: EB 04

At run time the CPU computes IP ← next IP + rel8 = 010Ah + 4 = 010Eh.

addressmachine codeinstruction0100hB8 05 00mov ax, 50103hBB 02 00mov bx, 20106hEB 02jmp calc0108hEB 04back: jmp stop010Ah01 D8calc: add ax, bx010ChEB FAjmp back010EhC3stop: retjmp back @ 010Chnext IP = 010Ehtarget back = 0108hrel8 = 0108 − 010E = −6−6 = FAh (two's complement)code: EB FA

Backward jump: the distance is negative and stored in two's complement: −6 → FAh. 010Eh + FFFAh = 0108h (the carry out is dropped).

Conditional Jumps

The Idea of a Conditional Jump

  • Jcc target: if the condition (cc) holds, IP ← target; otherwise the next instruction runs.
  • The condition depends on the flags set by an earlier instruction (usually CMP, SUB, ADD, TEST, DEC).
  • Jump instructions themselves do not change the flags.
ZFresult is zero
CFcarry / borrow
SFresult is negative
OFsigned overflow
PFeven number of 1s
AFnot used by jumps
cmp / sub / …flagscondition true?yeslabel:nonext instruction

Conditional Jumps

Jumps That Test a Single Flag

InstructionMeaningConditionOpposite
JZ, JEJump if Zero (Equal)ZF = 1JNZ, JNE
JC, JB, JNAEJump if Carry (Below, Not Above or Equal)CF = 1JNC, JNB, JAE
JSJump if Sign: result negativeSF = 1JNS
JOJump if Overflow: signed overflowOF = 1JNO
JPE, JPJump if Parity EvenPF = 1JPO, JNP
JNZ, JNEJump if Not Zero (Not Equal)ZF = 0JZ, JE
JNC, JNB, JAEJump if Not Carry (Not Below, Above or Equal)CF = 0JC, JB, JNAE
JNSJump if Not Sign: not negativeSF = 0JS
JNOJump if Not OverflowOF = 0JO
JPO, JNPJump if Parity Odd (No Parity)PF = 0JPE, JP

The "C" in JC is the carry flag; "overflow" refers to OF. They are different things.

Conditional Jumps

Encoding and Synonyms

  • On the 8086, conditional jumps have a fixed length: 2 bytes = opcode + a 1-byte displacement (rel8).
  • rel8 is always signed: relative to the next instruction, a jump can go 128 bytes back or 127 bytes forward.
  • Different names for the same condition (synonyms) assemble to the same machine code: JE = JZ, JNE = JNZ, JC = JB = JNAE, JNC = JNB = JAE.
  • Conditional jumps with 16-bit displacements (0F 8x) came only with the 80386; the 8086 does not have them.
74JE / JZ
75JNE / JNZ
72JB / JC / JNAE
73JAE / JNB / JNC
78JS
79JNS
70JO
71JNO
7AJP / JPE
7BJNP / JPO
77JA / JNBE
76JBE / JNA
7FJG / JNLE
7DJGE / JNL
7CJL / JNGE
7EJLE / JNG
E2LOOP
E1LOOPE / LOOPZ
E0LOOPNE / LOOPNZ
E3JCXZ

All are 2 bytes: opcode + rel8. The short JMP opcode is EBh.

Conditional Jumps · Step through the code

Code Trace: JNC = JNB = JAE

All three test the same condition (CF = 0) and produce the same opcode (73h); only rel8 differs, because each sits at a different address.

CF = 0, so jnc a jumps: IP ← 0102h + 07h = 0109h. The jnb, jae and mov ax, 4 in between do not run.

a: mov ax, 5 → AX = 0005h.

ret: IP ← 0000h. Had CF been 1, none of the three would jump, and AX would become 4, then 5.

org 100h
jnc a          ; 0100h: 73 07
jnb a          ; 0102h: 73 05
jae a          ; 0104h: 73 03
mov ax, 4      ; 0106h: B8 04 00
a: mov ax, 5   ; 0109h: B8 05 00
ret            ; 010Ch: C3

Conditional Jumps

Jump Code Calculator

Enter the address of the jump and the target address (hex) to get the rel8 / rel16 value and the machine code.

Rule: displacement = target − (address + instruction length). In the short form the result must be within −128…+127; otherwise the assembler reports "relative jump out of range".

Comparison

The CMP Instruction

  • Use CMP dest, src to compare numbers.
  • CMP performs a SUB: dest − src, but it discards the result; it only sets the flags (CF, ZF, SF, OF, PF, AF).
  • The conditional jump that follows decides based on these flags.
  • Operands: register–register, register–memory, memory–register, register/memory–immediate. Two memory operands are not allowed.
CMP 05h, 02h5 − 2 = 3 → 03hZF = 0, CF = 0, SF = 0, OF = 0
CMP 07h, 07h7 − 7 = 0 → 00hZF = 1, CF = 0, SF = 0, OF = 0
Example 1: 5 − 2 = 3 → the result is not zero, ZF = 0. Example 2: 7 − 7 = 0 → the result is zero, ZF = 1, and JE/JZ jumps.

Comparison

How Does CMP AL, BL Set the Flags?

AL0000 010105hunsigned 5 · signed 5BL0000 001002hunsigned 2 · signed 2AL−BL0000 001103hresult not kept, only the flagsCF=0ZF=0SF=0OF=0PF=1AF=0unsigned: AL > BLsigned: AL > BLCF=0, ZF=0 → JA jumpsSF=0, OF=0, ZF=0 → JG jumps

Positive difference: no flag is set except PF (PF = 1 because 03h = 0000 0011 has two 1s).

AL0000 011107hunsigned 7 · signed 7BL0000 011107hunsigned 7 · signed 7AL−BL0000 000000hresult not kept, only the flagsCF=0ZF=1SF=0OF=0PF=1AF=0unsigned: AL = BLsigned: AL = BLCF=0, ZF=1 → JE jumpsSF=0, OF=0, ZF=1 → JE jumps

Equal numbers: the result is 0 → ZF = 1. Equal whether signed or unsigned.

AL0000 010105hunsigned 5 · signed 5BL0000 011107hunsigned 7 · signed 7AL−BL1111 1110FEhresult not kept, only the flagsCF=1ZF=0SF=1OF=0PF=0AF=1unsigned: AL < BLsigned: AL < BLCF=1, ZF=0 → JB jumpsSF=1, OF=0, ZF=0 → JL jumps

Subtracting a larger number needs a borrow → CF = 1; the result FEh = −2 → SF = 1, no overflow.

AL0111 11117Fhunsigned 127 · signed 127BL1000 000080hunsigned 128 · signed -128AL−BL1111 1111FFhresult not kept, only the flagsCF=1ZF=0SF=1OF=1PF=1AF=0unsigned: AL < BLsigned: AL > BLCF=1, ZF=0 → JB jumpsSF=1, OF=1, ZF=0 → JG jumps

127 − (−128) = 255 does not fit in a signed byte → OF = 1. Unsigned, 127 < 128 (CF = 1); signed, 127 > −128 (SF = OF).

AL1111 1011FBhunsigned 251 · signed -5BL0000 001103hunsigned 3 · signed 3AL−BL1111 1000F8hresult not kept, only the flagsCF=0ZF=0SF=1OF=0PF=0AF=0unsigned: AL > BLsigned: AL < BLCF=0, ZF=0 → JA jumpsSF=1, OF=0, ZF=0 → JL jumps

FBh is 251 unsigned and −5 signed. Unsigned: 251 > 3 (CF = 0); signed: −5 < 3 (SF ≠ OF). Same bits, different decision!

Comparison

Comparison Calculator

Enter two bytes (decimal −128…255 or hex such as 7Fh) to see the result of CMP A, B, the flags and which jumps are taken.

Green: jumps · faded: does not jump

Comparison

Jumps for Signed Numbers

InstructionMeaningConditionOpposite
JE, JZJump if Equal (=) · Jump if ZeroZF = 1JNE, JNZ
JNE, JNZJump if Not Equal (<>) · Jump if Not ZeroZF = 0JE, JZ
JG, JNLEJump if Greater (>) · Not Less or EqualZF = 0 and SF = OFJNG, JLE
JL, JNGEJump if Less (<) · Not Greater or EqualSF ≠ OFJNL, JGE
JGE, JNLJump if Greater or Equal (>=) · Not LessSF = OFJNGE, JL
JLE, JNGJump if Less or Equal (<=) · Not GreaterZF = 1 or SF ≠ OFJNLE, JG
<> means "not equal". Greater / Less assume the numbers are signed, in two's complement.

Comparison

Why SF = OF?

  • CMP A, B computes A − B. Without overflow the sign of the result is correct: SF = 1 ⇔ A < B.
  • With overflow (OF = 1) the result did not fit in 8/16 bits and the sign bit is flipped.
  • So the true sign is SF XOR OF: SF ≠ OF ⇔ A < B, SF = OF ⇔ A ≥ B.
negative: 80h … FFhpositive: 00h … 7Fh−1280127127 + 1 → −128: at the end of the range the value wraps around and the sign bit flips (OF = 1)
ABA − B (8 bit)SFOFResult
57FEh (−2)10SF ≠ OF → 5 < 7
127 (7Fh)−128 (80h)FFh (−1) ✗ true: +25511SF = OF → 127 > −128
−128 (80h)17Fh (+127) ✗ true: −12901SF ≠ OF → −128 < 1
−5 (FBh)3F8h (−8)10SF ≠ OF → −5 < 3

In the overflow rows, SF alone would give the wrong answer; combined with OF the decision is correct.

Comparison

Jumps for Unsigned Numbers

InstructionMeaningConditionOpposite
JE, JZJump if Equal (=) · Jump if ZeroZF = 1JNE, JNZ
JNE, JNZJump if Not Equal (<>) · Jump if Not ZeroZF = 0JE, JZ
JA, JNBEJump if Above (>) · Not Below or EqualCF = 0 and ZF = 0JNA, JBE
JB, JNAE, JCJump if Below (<) · Not Above or Equal · CarryCF = 1JNB, JAE, JNC
JAE, JNB, JNCJump if Above or Equal (>=) · Not Below · Not CarryCF = 0JNAE, JB, JC
JBE, JNAJump if Below or Equal (<=) · Not AboveCF = 1 or ZF = 1JNBE, JA
In unsigned subtraction, if A < B a borrow occurs and CF = 1. So the "below" test is just the carry flag: JB ≡ JC.

Comparison

Above/Below or Greater/Less?

ComparisonUnsigned (A/B)Signed (G/L)
A = BJE / JZJE / JZ
A ≠ BJNE / JNZJNE / JNZ
A > BJA / JNBEJG / JNLE
A ≥ BJAE / JNBJGE / JNL
A < BJB / JNAEJL / JNGE
A ≤ BJBE / JNAJLE / JNG
MnemonicAbove / Below → unsigned (addresses, counters, ASCII codes). Greater / Less → signed (temperatures, differences, values that may be negative).
Typical bugWith AL = FBh, BL = 03h, JA jumps (251 > 3) but JG does not (−5 < 3). Choose the family that matches the data.

Comparison · Step through the code

Code Trace: Same Bits, JA and JG

ALFBhBL03hCH00hDL00hCF0ZF0SF0OF0AL = 251signed -5

AL = FBh: unsigned 251, signed −5. BL = 3. CL, CH, DL will mark which jump was not taken.

ALFBhBL03hCH00hDL00hCF0ZF0SF1OF0AL = 251signed -5

CMP AL, BL: FBh − 03h = F8h. No borrow → CF = 0; negative result → SF = 1; no overflow → OF = 0.

ALFBhBL03hCH00hDL00hCF0ZF0SF1OF0AL = 251signed -5JA → jumps

JA: CF = 0 and ZF = 0 → jumps (251 > 3). The CL = 1 line is skipped.

ALFBhBL03hCH00hDL00hCF0ZF0SF1OF0AL = 251signed -5JG → no jump

JG: ZF = 0 but SF ≠ OF → no jump (−5 < 3).

ALFBhBL03hCH01hDL00hCF0ZF0SF1OF0AL = 251signed -5

CH = 1: in the signed comparison AL is not greater. One CMP, two different decisions.

AL7FhBL03hCH01hDL00hCF0ZF0SF1OF0AL = 127signed 127

AL = 7Fh = 127. Now compare 127 with 80h (−128).

AL7FhBL03hCH01hDL00hCF1ZF0SF1OF1AL = 127signed 127

7Fh − 80h = FFh: signed 127 − (−128) = 255 does not fit → OF = 1, the result's sign bit SF = 1. Borrow → CF = 1.

AL7FhBL03hCH01hDL00hCF1ZF0SF1OF1AL = 127signed 127JG → jumps

JG: ZF = 0 and SF = OF (1 = 1) → jumps: 127 > −128 is true. SF alone would have said “less”.

AL7FhBL03hCH01hDL00hCF1ZF0SF1OF1AL = 127signed 127

DL stays 0. Result: CH = 1 (−5 > 3 is false), DL = 0 (127 > −128).

MOV  AL, 0FBh    ; 251 or -5
MOV  BL, 03h
CMP  AL, BL      ; FBh - 03h
JA   a1          ; unsigned: 251 > 3 ?
MOV  CL, 1       ; if JA failed
a1:  JG  g1      ; signed: -5 > 3 ?
MOV  CH, 1       ; JG not taken
g1:  MOV AL, 7Fh ; 127
CMP  AL, 80h     ; 127 - (-128)
JG   g2          ; SF = OF ?
MOV  DL, 1       ; if JG failed
g2:  RET

Comparison · Step through the code

Code Trace: CMP + JE

AX = 0005h.

BX = 0005h.

cmp ax, bx: 5 − 5 = 0 → ZF = 1. AX is unchanged.

ZF = 1, so je jumps.

equal_message: the work for the equal case goes here.

jmp end_program: skips the not_equal_message block. Without this JMP both blocks would run.

End of program. If they were not equal, je would not jump and the jmp on line 5 would go to line 8.

mov ax, 5
mov bx, 5
cmp ax, bx
je  equal_message
jmp not_equal_message
equal_message:        ; if equal
jmp end_program
not_equal_message:    ; if not equal
end_program:

Comparison · Step through the code

Code Trace: CMP + JA

AX = 0005h.

BX = 0007h.

cmp ax, bx: 5 − 7 = FFFEh (−2). Borrow → CF = 1, ZF = 0.

ja needs CF = 0 and ZF = 0. CF = 1 → no jump.

jmp not_jump_above goes to the "less or equal" block.

not_jump_above: the work for AX ≤ BX.

End of program. Using jg instead of ja would not jump either (SF ≠ OF); with positive values both families agree.

mov ax, 5
mov bx, 7
cmp ax, bx
ja  jump_above
jmp not_jump_above
jump_above:       ; if ax is greater
jmp end_program
not_jump_above:   ; if ax is less/equal
end_program:

Comparison · Step through the code

Code Trace: Compare and Print

The character is printed with a DOS service: INT 21h with AH = 02h prints the character in DL.

AL = 25 = 19h.

BL = 10 = 0Ah.

cmp al, bl: 25 − 10 = 15 (0Fh) → ZF = 0.

ZF = 0 → je does not jump.

mov dl, 'n': the character to print is in DL (6Eh).

jmp prt: skips the 'y' line; both branches meet at the prt label.

AH = 02h: DOS character output service.

int 21h: prints n. DOS also leaves the printed character in AL: AL = 6Eh.

A program must end with ret; otherwise the CPU would execute the random bytes that follow as instructions.

org    100h
mov    al, 25     ; al = 25
mov    bl, 10     ; bl = 10
cmp    al, bl     ; compare al - bl
je     equal      ; jump if al = bl (zf = 1)
mov    dl, 'n'    ; al <> bl: print 'n'
jmp    prt        ; go to the print line
equal:
mov    dl, 'y'    ; al = bl: print 'y'
prt:
mov    ah, 2      ; DOS: print char in DL
int    21h
ret               ; return to DOS

Comparison

The if / else Pattern

High Level

if (ax == bx) {
    ; block A
} else {
    ; block B
}
while (cx > 0) {     ; unsigned
    ; body
}

Assembly

    cmp ax, bx
    jne not_eq     ; the OPPOSITE test
    ; block A
    jmp after
not_eq:
    ; block B
after:
top: cmp cx, 0
    jbe done       ; cx <= 0 → exit
    ; body
    jmp top
done:
Skipping a block with the opposite condition keeps the code in the same order as the high-level version. Forget the jmp after at the end of block A, and block B runs too.

Comparison · Step through the code

Code Trace: if / else and while

AX000ChBX001EhCX0000hDX0000hZF0CF0block Ablock Bloop body

if (AX == BX) DX = 1; else DX = 2; then, with CX = 2, while (CX > 0) DX += CX. AX = 12, BX = 30.

AX000ChBX001EhCX0000hDX0000hZF0CF1block Ablock Bloop body

CMP AX, BX: 12 − 30 → ZF = 0 (not equal), borrow → CF = 1.

AX000ChBX001EhCX0000hDX0000hZF0CF1block Ablock Bloop bodyJNE → jumps

JNE not_eq: the opposite condition holds → block A is skipped.

AX000ChBX001EhCX0000hDX0002hZF0CF1block Ablock Bloop body

Block B: DX = 2. The next line is after; the JMP after in block A was not needed on this path.

AX000ChBX001EhCX0002hDX0002hZF0CF0block Ablock Bloop bodyJBE → no jump

CX = 2. CMP CX, 0: 2 > 0 → CF = 0, ZF = 0; JBE does not jump, the body is entered.

AX000ChBX001EhCX0001hDX0004hZF0CF0block Ablock Bloop body

Body: DX = 2 + 2 = 4; CX = 1.

AX000ChBX001EhCX0001hDX0004hZF0CF0block Ablock Bloop bodyJBE → no jump

JMP top: the condition is tested again; 1 > 0 → JBE does not jump.

AX000ChBX001EhCX0000hDX0005hZF1CF0block Ablock Bloop body

DX = 4 + 1 = 5; CX = 0 → DEC sets ZF = 1.

AX000ChBX001EhCX0000hDX0005hZF1CF0block Ablock Bloop bodyJBE → jumps

Back at the top: CX = 0 → ZF = 1, JBE done jumps. Because the condition is tested first, CX = 0 would never enter the loop.

AX000ChBX001EhCX0000hDX0005hZF1CF0block Ablock Bloop body

Result DX = 5: block B (2) + 2 + 1.

MOV  AX, 12
MOV  BX, 30
CMP  AX, BX
JNE  not_eq      ; OPPOSITE test
MOV  DX, 1       ; block A: AX = BX
JMP  after
not_eq: MOV DX, 2 ; block B: AX ≠ BX
after: MOV CX, 2 ; while (CX > 0)
top: CMP CX, 0
JBE  done        ; CX ≤ 0 → exit
ADD  DX, CX      ; body
DEC  CX
JMP  top
done: RET

Comparison

Out-of-Range Conditional Jump

  • On the 8086 a conditional jump reaches only −128…+127 bytes.
  • If the target is farther, the assembler reports an error. Fix: invert the condition, short-jump over the next instruction, and reach the far target with a JMP (near, ±32 KB).
  • emu8086 does this rewrite itself, turning an out-of-range Jcc into an inverted short jump plus a JMP; assemblers such as MASM report an error.
Jcc range: −128 … +127next IPfar_away+200 bytesJMP near: anywhere in the segment (±32 KB)

Wrong (target too far)

cmp al, 0
je  far_away    ; out of range!
; ... 200 bytes of code ...
far_away:

Right

cmp al, 0
jne cont        ; opposite test, short
jmp far_away    ; near JMP (E9)
cont:
; ... 200 bytes of code ...
far_away:

Loops

Loop Instructions

InstructionOperation and jump condition
LOOPDecrement CX; jump if CX ≠ 0.
LOOPEDecrement CX; jump if CX ≠ 0 and equal (ZF = 1).
LOOPZSame as LOOPE: jump if CX ≠ 0 and ZF = 1.
LOOPNEDecrement CX; jump if CX ≠ 0 and not equal (ZF = 0).
LOOPNZSame as LOOPNE: jump if CX ≠ 0 and ZF = 0.
JCXZJump if CX = 0 (CX is not decremented).
CX ← CX − 1CX ≠ 0 (+ ZF test)?yesjump to labelnonext instructionflags unchanged
CounterThe counter is always the CX register.
FlagsThe LOOP family decrements CX without changing the flags.
RangeAll are 2 bytes, rel8: at most 128 bytes back.

Loops

How Does LOOP Work?

  • Loops repeat a block of code depending on a condition.
  • LOOP target: CX is decremented first; if it is not zero, jump to the label. Same effect as DEC CX + JNZ, but the flags are preserved.
  • LOOPE / LOOPZ jumps while CX ≠ 0 and ZF = 1; LOOPNE / LOOPNZ while CX ≠ 0 and ZF = 0.
  • JCXZ: jumps to the label when CX is zero.
  • With CX = 0 on entry, the first decrement makes CX FFFFh → the body runs 65,536 times.
mov cx, nlabel:loop bodyCX ← CX − 1CX ≠ 0 ?yesno → next instructionLOOPE: and ZF=1LOOPNE: and ZF=0

Loops · Step through the code

Code Trace: LOOP

CX = 0005h: the body will run 5 times.

Pass 1: the loop body runs.

loop: CX = 0004h ≠ 0 → jump back to again.

Pass 2: the loop body runs.

loop: CX = 0003h ≠ 0 → jump back to again.

Pass 3: the loop body runs.

loop: CX = 0002h ≠ 0 → jump back to again.

Pass 4: the loop body runs.

loop: CX = 0001h ≠ 0 → jump back to again.

Pass 5: the loop body runs.

loop: CX = 0000h → no jump, the loop exits.

jmp quit: quit is already the next line, so this jump is unnecessary but harmless.

ret: the body ran 5 times in total.

org 100h
mov cx, 5         ; CX = repeat count
again:
; loop body
loop again        ; if CX ≠ 0 go to again
jmp quit          ; loop done: go to quit
quit:
ret

Loops · Step through the code

Code Trace: Nested LOOPs

BX counts the total steps: 0. In a .COM program SP = FFFEh.

The outer loop will run 5 times: CX = 0005h.

Outer pass 1: BX = 1.

AL = '1' (31h), AH = 0Eh → INT 10h teletype prints 1. (Function 0Eh uses BH as the page number; BX < 256, so BH = 0.)

push cx: the inner loop also uses CX, so the outer counter (5) is saved on the stack; SP = FFFCh.

Inner loop counter: CX = 5.

Inner pass 1: BX = 2, prints 2.

loop k2: CX = 4 → back to k2.

4 more inner passes: 5 2s printed in total, BX = 6, CX = 0 → the inner loop ends.

pop cx: the outer counter is back: CX = 5, SP = FFFEh.

loop k1: CX = 4 → back to k1 (outer pass 2).

Outer pass 2 done: BX = 12, CX = 3.

Outer pass 3 done: BX = 18, CX = 2.

Outer pass 4 done: BX = 24, CX = 1.

Outer pass 5 done: CX = 0 → the outer loop exits. BX = 30 = 001Eh (5 + 5×5 steps).

ret. The screen shows "122222" 5 times. Because push/pop are balanced, ret returns to the right address (0000h); SP = 0000h.

org 100h
mov bx, 0      ; total steps
mov cx, 5      ; outer counter
k1:
 add bx, 1
 mov al, '1'
 mov ah, 0eh
 int 10h       ; print '1'
 push cx       ; save outer
 mov cx, 5     ; inner counter
k2:
  add bx, 1
  mov al, '2'
  mov ah, 0eh
  int 10h      ; print '2'
  loop k2      ; inner loop
 pop cx        ; restore outer
loop k1        ; outer loop
ret

Loops · Step through the code

Code Trace: Searching an Array with LOOPNE

7[0]1[1]3[2]9[3]4[4]

At most 5 elements will be examined.

7[0]1[1]3[2]9[3]4[4]

SI = −1 (FFFFh); the first inc in the loop makes it 0.

7[0]1[1]3[2]9[3]4[4]SI

SI = 0.

7[0]1[1]3[2]9[3]4[4]SI

arr[0] = 7; 7 − 3 → ZF = 0.

7[0]1[1]3[2]9[3]4[4]SI

loopne: CX = 4 ≠ 0 and ZF = 0 → keep searching.

7[0]1[1]3[2]9[3]4[4]SI

SI = 1.

7[0]1[1]3[2]9[3]4[4]SI

arr[1] = 1; 1 − 3 → ZF = 0.

7[0]1[1]3[2]9[3]4[4]SI

loopne: CX = 3 ≠ 0 and ZF = 0 → keep searching.

7[0]1[1]3[2]9[3]4[4]SI

SI = 2.

7[0]1[1]3[2]9[3]4[4]SI

arr[2] = 3; 3 − 3 → ZF = 1.

7[0]1[1]3[2]9[3]4[4]SI

loopne: CX = 2 but ZF = 1 → the loop exits. LOOPNE does not change the flags, so ZF = 1 survives.

7[0]1[1]3[2]9[3]4[4]SI

ZF = 1 → jne notfound does not jump: the value was found.

7[0]1[1]3[2]9[3]4[4]SI

AL = 1 (found), SI = 2 gives the position. The loop finished in 3 passes instead of 5.

org 100h
mov cx, 5          ; element count
mov si, -1         ; first inc makes it 0
scan:
inc si             ; next element
cmp arr[si], 3     ; is it 3?
loopne scan        ; go on if CX≠0, ZF=0
jne notfound       ; ZF=0 → not found
mov al, 1          ; found, position in SI
ret
notfound:
mov al, 0          ; not found
ret
arr db 7, 1, 3, 9, 4

Loops

JCXZ and LOOP / DEC–JNZ

Guarding against a zero-pass loop

mov cx, n        ; n known at run time
jcxz skip        ; skip if CX = 0
again:
    ; body
    loop again
skip:

Without JCXZ, LOOP with CX = 0 first makes CX FFFFh and the body runs 65,536 times.

LOOP or DEC + JNZ?

LOOPDEC CX + JNZ
Size2 bytes1 + 2 = 3 bytes
FlagsunchangedZF, SF, OF, PF, AF change (CF kept)
CounterCX onlyany register
Extra conditionLOOPE / LOOPNEany Jcc can be chosen

Loops · Step through the code

Code Trace: JCXZ Guard and DEC–JNZ

AX0000hBX0000hCX0000hZF0CF0

The pass count n = 0 is in CX. An unguarded LOOP would first make CX FFFFh and run the body 65,536 times.

AX0000hBX0000hCX0000hZF0CF0JCXZ → jumps

JCXZ skip: CX = 0 → the loop is never entered. AX stays 0.

AX0000hBX0003hCX0000hZF0CF0

Second loop: counter BX = 3 (DEC–JNZ can use any register).

AX0000hBX0003hCX0000hZF0CF1

STC: CF = 1. Think of it as information that must survive the loop.

AX0001hBX0002hCX0000hZF0CF1JNZ → jumps

Pass 1: AX = 1. DEC BX → 2, ZF = 0 → JNZ jumps back. CF is still 1.

AX0002hBX0001hCX0000hZF0CF1JNZ → jumps

Pass 2: AX = 2, BX = 1.

AX0003hBX0000hCX0000hZF1CF1

Pass 3: AX = 3. DEC BX → 0, ZF = 1. INC/DEC did not touch CF: CF = 1.

AX0003hBX0000hCX0000hZF1CF1JNZ → no jump

JNZ: ZF = 1 → no jump, the loop ends.

AX0003hBX0000hCX0000hZF1CF1

Result AX = 3, CF = 1 preserved. LOOP does not change flags either, but works only with CX.

MOV  CX, 0       ; n = 0
MOV  AX, 0
JCXZ skip        ; CX = 0 → skip
again: INC AX
LOOP again
skip: MOV BX, 3  ; n = 3, counter BX
STC              ; CF = 1
again2: INC AX
DEC  BX          ; CF is kept
JNZ  again2
RET

Example Programs · Step through the code

Code Trace: Sum of Array Elements

5[0]4[1]5[2]2[3]1[4]BX

CX = 5 elements, sum AL = 0, index BX = 0.

5[0]4[1]5[2]2[3]1[4]BX

add al, vector[0]: AL = 0 + 5 = 5 (05h).

5[0]4[1]5[2]2[3]1[4]BX

BX = 1, CX = 4 → back to next.

5[0]4[1]5[2]2[3]1[4]BX

add al, vector[1]: AL = 5 + 4 = 9 (09h).

5[0]4[1]5[2]2[3]1[4]BX

BX = 2, CX = 3 → back to next.

5[0]4[1]5[2]2[3]1[4]BX

add al, vector[2]: AL = 9 + 5 = 14 (0Eh).

5[0]4[1]5[2]2[3]1[4]BX

BX = 3, CX = 2 → back to next.

5[0]4[1]5[2]2[3]1[4]BX

add al, vector[3]: AL = 14 + 2 = 16 (10h).

5[0]4[1]5[2]2[3]1[4]BX

BX = 4, CX = 1 → back to next.

5[0]4[1]5[2]2[3]1[4]BX

add al, vector[4]: AL = 16 + 1 = 17 (11h).

5[0]4[1]5[2]2[3]1[4]

BX = 5, CX = 0 → the loop ends.

5[0]4[1]5[2]2[3]1[4]

mov m, al: m = 11h = 17 = 5 + 4 + 5 + 2 + 1.

5[0]4[1]5[2]2[3]1[4]

ret. The data is defined after ret, so it is never executed as code.

org 100h
mov cx, 5           ; element count
mov al, 0           ; sum (AL) = 0
mov bx, 0           ; BX = index
next:
add al, vector[bx]  ; add element
inc bx              ; next element
loop next           ; until CX = 0
mov m, al           ; store in m
ret
vector db 5, 4, 5, 2, 1
m db 0

Example Programs · Step through the code

Code Trace: Printing Hello on the Screen

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000h

jmp start: the data (msg) sits between instructions, so it is jumped over; otherwise bytes such as 'H' (48h) would be taken as instructions.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

SI = 0: first character.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

AL = msg[0] = 'H' = 48h.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

48h − 0 ≠ 0 → ZF = 0, je does not jump.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

AH = 0Eh, INT 10h → prints H.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

SI = 1, jmp next_char goes back to the top.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

Next pass: AL = 'e' (65h), ZF = 0 → prints e, SI = 2.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

Next pass: AL = 'l' (6Ch), ZF = 0 → prints l, SI = 3.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

Next pass: AL = 'l' (6Ch), ZF = 0 → prints l, SI = 4.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

Next pass: AL = 'o' (6Fh), ZF = 0 → prints o, SI = 5.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

AL = msg[5] = 0: end of the string (null terminator).

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI

0 − 0 = 0 → ZF = 1, je stop jumps.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000h

ret: the screen shows Hello.

org     100h
jmp     start
msg db 'Hello', 0
start:
mov     si, 0          ; source index = 0
next_char:
mov     al, msg[si]    ; get the char
cmp     al, 0          ; compare with 0
je      stop           ; stop if 0
mov     ah, 0eh        ; teletype function
int     10h            ; print char in AL
inc     si             ; next character
jmp     next_char      ; loop back
stop:
ret

Example Programs

Palindrome Check: The Idea

  • Palindrome: a string that reads the same forward and backward (123321, kayak).
  • DI points to the start of the string and SI to its end; the characters are compared, DI moves forward and SI backward.
  • Comparing half the length is enough (shr cx, 1 → CX / 2). With an odd length the middle character is not compared.
  • str_size = $ - msg: $ is the current address; msg and str are at the same address, so the result is the constant 6, the string length (it takes no memory).
  • INT 21h / AH = 09h prints the string at DS:DX up to the '$' character; 0Dh, 0Ah are carriage return and line feed.
'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

Addresses assume org 100h and a 2-byte short jmp start (0100h): str starts at 0102h.

Example Programs · Step through the code

Code Trace: Palindrome (1/2) Setup

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

jmp start: jumps over the data section.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

AH = 09h: DOS string output function.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

DX = offset str = 0102h.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

INT 21h: prints 123321 and a line break ('$' is not printed).

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDIstr_size = 6

lea di, str: DI = 0102h (first character).

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

SI = DI = 0102h.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

SI = 0102h + 6 = 0108h: one past the string (0Dh).

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

dec si: SI = 0107h, the last character '1'.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

CX = str_size = 6.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

6 − 1 ≠ 0 → ZF = 0, je does not jump.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

shr cx, 1: 0110b → 0011b, CX = 3. The bit shifted out is 0 → CF = 0.

org 100h
jmp start
msg:
str db '123321'
str_size = $ - msg     ; = 6
db 0Dh,0Ah,'$'
start:
mov ah, 9              ; print up to '$'
mov dx, offset str
int 21h
lea di, str            ; DI = address of str
mov si, di
add si, str_size       ; SI = last + 1
dec si                 ; SI = last char
mov cx, str_size
cmp cx, 1              ; one character?
je is_palindrome       ; one char is a palindrome
shr cx, 1              ; CX = length / 2

Example Programs · Step through the code

Code Trace: Palindrome (2/2) Comparison

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

Loop start: DI = 0102h, SI = 0107h, CX = 3.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

AL = [DI] = '1', BL = [SI] = '1'.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

Equal → ZF = 1, jne does not jump.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

DI = 0103h, SI = 0106h (the INC/DEC result is nonzero → ZF = 0), CX = 2 → next_char.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

AL = [DI] = '2', BL = [SI] = '2'.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

Equal → ZF = 1, jne does not jump.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

DI = 0104h, SI = 0105h, CX = 1 → next_char.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

AL = [DI] = '3', BL = [SI] = '3'.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

Equal → ZF = 1, jne does not jump.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6

CX = 0 → the loop ends: every pair matched.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

AH = 09h, DX = offset msg1 = 0142h.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

INT 21h: prints palindrome! (DOS returns from this function with AL = 24h, i.e. '$'.)

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

jmp stop: skips the "not palindrome!" block.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010Ahstr_size = 6

ret. The data comes right after the stop: label, so without ret the CPU would execute the bytes of "palindrome!$" as instructions.

next_char:
mov al, [di]          ; char at the start
mov bl, [si]          ; char at the end
cmp al, bl
jne not_palindrome    ; differ: not one
inc di                ; start: one forward
dec si                ; end: one back
loop next_char
is_palindrome:
mov ah, 9             ; print "palindrome!"
mov dx, offset msg1
int 21h
jmp stop
not_palindrome:
mov ah, 9             ; "not palindrome!"
mov dx, offset msg2
int 21h
stop:
ret
msg1 db "palindrome!$"
msg2 db "not palindrome!$"

Example Programs

Palindrome: Different Inputs

strLengthCX (after shr)ComparisonsOutput
'123321'631=1, 2=2, 3=3palindrome!
'123421'631=1, 2=2, 3≠4 → jnenot palindrome!
'12321'521=1, 2=2 (the middle 3 is skipped)palindrome!
'7'1—cmp cx,1 → je is_palindromepalindrome!
'ab'21a≠b → jnenot palindrome!
Why cmp cx, 1? With length 1, shr cx, 1 makes CX 0; entering a LOOP-based loop with CX = 0 would run the comparison 65,536 times. Length 0 has the same danger: guard it with jcxz.

Lab · 8086 instructions step by step

Lab: Jumps and Loops

Summary

Summary

JMPUnconditional; IP ← target. Short (EB, −128…+127), near (E9, within segment), far (EA, CS:IP).
Displacementtarget − address of the next instruction; stored in two's complement if negative.
JccTests the flags without changing them; on the 8086 short only (2 bytes).
CMPA SUB that keeps no result; the Jcc that follows makes the decision.
UnsignedJA, JAE, JB, JBE → CF and ZF.
SignedJG, JGE, JL, JLE → ZF, SF and OF.
LOOP familyCX is decremented, flags are preserved; LOOPE/LOOPNE also test ZF.
PitfallsLOOP with CX = 0, not saving CX in nested loops, executing data as code.

Summary

Exercises

  1. The JNE at address 0120h must jump to address 0100h. What is its machine code?
  2. After mov al, 80h / cmp al, 1, do JA and JG jump?
  3. How many times does mov cx, 0 / d: loop d run? How do you prevent it?
  4. Write code that sets BX = 1 if the unsigned number in AX is greater than 100, and BX = 0 otherwise.
  5. In the array sum example, what would AL and CF be if the elements were 200 and 100? Suggest a fix.
  6. What happens in the Hello example if the jmp start line is deleted?
Hints / answers
  1. Next IP = 0122h; 0100h − 0122h = −22h = DEh → 75 DE.
  2. 80h − 01h = 7Fh: CF = 0, ZF = 0 → JA jumps (128 > 1). SF = 0, OF = 1 → SF ≠ OF → JG does not jump (−128 < 1).
  3. 65,536 times; put a jcxz before it.
  4. mov bx, 0 / cmp ax, 100 / jbe done / mov bx, 1 / done:
  5. 200 + 100 = 300 = 12Ch → AL = 2Ch, CF = 1 (carry). Keep the sum in AX and use adc ah, 0, or add in 16 bits.
  6. The bytes 'H','e','l','l','o',0 (48h 65h 6Ch …) are executed as instructions; the program behaves unpredictably.

Summary

References

  • emu8086 documentation: 8086 Assembler Tutorial for Beginners (Part 7: Program Flow Control).
  • Intel, The 8086 Family User's Manual, 1979: instruction set and encoding tables.
  • Barry B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009: Chapter 6 "Program Control Instructions".
  • Kip R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014: conditional processing and loops.

The End

Chapter 7: Flow Control
Previous: Chapter 6: Arithmetic, Logic and Shift Instructions · Next: Chapter 8.1: The Stack
1 / 1 Sercan KÜLCÜ. All rights reserved.