So far every program in this series has run straight from top to bottom. Real programs branch: they choose a path, repeat a block, or skip one. This tutorial covers the three mechanisms that make that possible. It builds on MOV, ADD and SUB and the flags they set, and it assumes Emu8086 is installed; see the install guide.
Unconditional jumps
JMP always goes to its label. It is the simplest branch and also the easiest to misuse: a program full of unconditional jumps quickly becomes hard to follow, so use it for a clear purpose, such as skipping over a block or jumping to a shared ending.
Conditional jumps read the flags
Instructions such as JE, JNE, JG and JL jump only when the flags say so. They are almost always paired with a CMP, which subtracts without storing the result, purely to set the flags. The example below sets BL to 1 when AL equals 10 and to 0 otherwise. Step through it twice: once with AL equal to 10, once with a different value, by editing the first instruction.
ORG 100h MOV AL, 10 CMP AL, 10 JE is_ten MOV BL, 0 JMP done is_ten: MOV BL, 1 done: RET
What you should see
With AL equal to 10, the jump is taken, the MOV BL, 0 line is skipped, and BL ends up as 1. With AL equal to anything else, the jump is not taken, BL is set to 0, and the JMP done skips over the is_ten block. If BL ends up wrong, check that no MOV sits between the CMP and the jump and accidentally hides the flags you meant to test; MOV itself does not change the flags, but a stray arithmetic instruction between them would.
Counted loops with LOOP
The LOOP instruction decrements CX and jumps back while CX is not zero. It is made for counted repetition. The program below adds 5, 4, 3, 2 and 1, so the total should be 15. Watch CX fall on each pass and AX grow.
ORG 100h MOV CX, 5 XOR AX, AX add_next: ADD AX, CX LOOP add_next RET
What you should see
AX should end at 15 and CX at 0. Two details are worth noting. First, LOOP itself does not set the flags, so do not test the zero flag right after a loop expecting it to reflect CX. Second, if CX starts at 0, LOOP wraps it to a very large value and the loop runs a very long time, so always check that CX is loaded before the loop starts.
Choosing between the three
- Use
JMPwhen the path is unconditional, such as skipping a block. - Use a
CMPplus a conditional jump when the path depends on a value. - Use
LOOPwith CX when you know in advance how many times a block must run.
Next steps
Loops over data are next in arrays and strings, and subroutines and the stack show how a repeated block becomes a callable routine. The opcode reference covers every jump condition, and the home page is the series index.
