Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 40 ยท Control Flow

Compare and Jump

Learn how assembly makes decisions: CMP and TEST set flags, then JE, JNE, JL, JG, JA and JB jump. Includes labels, relative jumps and a runnable toy CPU.

A high-level language has if, while and for. A CPU has none of them. All it can do is run the next instruction, or change which instruction comes next. Every decision in a program, whatever the language, is built from one small pattern: do a comparison that sets flags, then jump if the flags say so. In this lesson you learn that pattern, the many conditional jump instructions, and what a jump really is at the byte level.

You should already know that arithmetic leaves traces in the CPU's flags (Flags: ZF, SF, CF, OF). Here we put those flags to work. The examples run on an x86-flavoured variant of the toy CPU from Meet the Toy CPU: the same ideas (registers, four flags, a stack, labels), but with register names borrowed from x86-64 (rax, rbx, ...), 32-bit values, and extra instructions such as inc, dec, test, loop and cmovcc. Every TryIt below carries its own copy of the interpreter, with the program at the top and the interpreter at the bottom, so you can edit the assembly and press Run.

Labels and the unconditional jump

A label is a name for a position in the program. You write it on its own line, ending in a colon. The assembler turns each label into an address (or, in our toy, an instruction number), so you never count instructions yourself.

jmp label always continues at the label. A backwards jmp makes a loop that never ends; a forward jmp skips code. Together with the conditional jumps below, jmp is the glue for every structured construct, such as the "skip the else part" jump at the end of an if block.

NASM
        jmp   skip        ; always jump
        mov   eax, 1      ; never executed
skip:
        mov   eax, 2

CMP and TEST: compare without keeping the answer

cmp a, b computes a - b, throws the result away and keeps only the flags. It is a subtraction whose answer nobody wants, only its side effects. After cmp rax, rbx:

  • ZF is 1 when the two values are equal (the difference was zero).
  • SF and OF together tell whether rax < rbx when both are read as signed numbers.
  • CF tells whether rax < rbx when both are read as unsigned numbers (a borrow happened).

test a, b does the same trick with a bitwise AND: it computes a & b, discards the result and sets ZF and SF from it (CF and OF become 0). It is the instruction for questions about bits. test rax, rax ANDs a value with itself, so ZF is 1 exactly when the value is zero, a shorter check than cmp rax, 0. test rax, 1 asks "is the lowest bit set?", which means "is it odd?".

The conditional jump family

A conditional jump, written jcc where cc is a condition code, looks at the flags. If the condition holds it jumps, otherwise execution simply continues with the next instruction.

Instruction Meaning after cmp a, b Flags tested Reading
je / jz a == b ZF = 1 equal, or zero
jne / jnz a != b ZF = 0 not equal
jl a < b SF != OF signed less
jle a <= b ZF = 1 or SF != OF signed less or equal
jg a > b ZF = 0 and SF = OF signed greater
jge a >= b SF = OF signed greater or equal
jb a < b CF = 1 unsigned below
jbe a <= b CF = 1 or ZF = 1 unsigned below or equal
ja a > b CF = 0 and ZF = 0 unsigned above
jae a >= b CF = 0 unsigned above or equal

Two families, one rule to remember: greater/less is for signed numbers, above/below is for unsigned numbers. The CPU does not know whether your 32 bits mean -1 or 4,294,967,295; you tell it by choosing jl or jb. A compiler picks the family from the C type: int gives jl, unsigned gives jb. Using the wrong one is a classic bug, and a classic source of security holes when a length check is done with signed jumps.

A few more exist: js/jns (sign flag), jo/jno (overflow), jc/jnc (carry, the same as jb/jae). Many names are synonyms: jz is je, and jnb is jae.

flowchart LR
  A["cmp rax, rbx"] --> B["flags set<br/>ZF SF CF OF"]
  B --> C{"jcc: condition true?"}
  C -- "yes" --> D["continue at label"]
  C -- "no" --> E["next instruction"]

Compare first, then let one conditional jump read the flags it left behind.

Your first branch

The toy CPU keeps four flags and supports all the jumps above. This program finds the larger of two numbers. The trace shows the registers and flags before each instruction runs, so the flags you see on the jge line were produced by the cmp line above it.

JS Maximum of two numbers, with a trace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that line 6 (mov rcx, rax) never appears in the trace: the branch to a_is_max was not taken, and the jmp done skipped it. Change mov rax, 7 to mov rax, 20 and the trace takes the other path. The shape (compare, conditional jump over a block, unconditional jump over the other block) is exactly how a compiler lays out an if/else, which you will study in How if, switch and Ternaries Compile.

Signed or unsigned? Ask all the jumps

The same bits give different answers under the two families. This TryIt builds a tiny program for every condition code, runs it, and prints which jumps would be taken for three pairs. Look at the pair -1 and 1: in the toy CPU -1 is the pattern 0xFFFFFFFF.

JS Which conditional jumps are taken?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For cmp -1, 1 the output contains jl (signed: -1 is less than 1) and ja (unsigned: 4,294,967,295 is above 1). For 5, 9 the signed and unsigned answers agree, which is why such bugs hide until a value gets large or negative.

TEST and the zero check

test shines when you only care about bits. The program below classifies a number as zero, odd or even without ever naming a second number.

JS Zero, odd or even with TEST

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try the three values from the comment. Zero is also even, but the program reports it as zero because the first check wins: the order of your tests is part of your logic.

Jumps at the byte level: relative offsets

On real x86-64, the common jump encodings do not store a destination address. They store a relative offset, the distance from the end of the jump instruction to the target. The short form of jmp is EB plus one signed byte; the short je is 74 plus one signed byte. Here is a small real function, read-only, as objdump would show it for code that returns 1 when its argument is not 10 (annotated):

NASM
 0:  83 ff 0a          cmp   edi, 10
 3:  74 05             je    0xa        ; offset +5 from the end of this 2-byte instruction (5 + 5 = 0xa)
 5:  b8 01 00 00 00    mov   eax, 1
 a:  c3                ret

Because the offset is relative, you can copy this code to another address and every jump still works. That property is called being position independent and it is why shared libraries can be loaded anywhere. When a target is too far for one byte (more than 127 bytes forward or 128 back) the assembler picks a longer form with a 32-bit offset, and you never notice. ARM64 works the same way with b and b.cond, which hold an offset counted in 4-byte instructions; for example cmp w0, w1 followed by b.lt label mirrors cmp plus jl (see ARM Load/Store, Conditions and Branches).

A conditional jump must run right after the instruction whose flags it wants. Almost any arithmetic instruction overwrites the flags, so putting an add between the cmp and the jl silently changes which condition the jump sees.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cmp rax, rbx do?

    cmp is a subtraction whose result is thrown away. Only ZF, SF, CF and OF survive, and a following jcc reads them.
  2. 2. A program compares two numbers that might be negative. Which jump should test "first is less than second"?

    jl looks at SF and OF, which describe the signed result. jb looks at CF and treats the values as unsigned, so -1 would count as a huge number.
  3. 3. After cmp of the bit patterns 0xFFFFFFFF and 1, which pair of jumps are both taken?

    As signed numbers -1 < 1, so jl is taken. As unsigned numbers 4,294,967,295 > 1, so ja is taken. The same bits, two readings.
  4. 4. Why does test rax, rax followed by jz check for zero?

    x AND x equals x, so the result is zero only for x = 0. test keeps only the flags, so ZF = 1 exactly in that case.

Summary

  • Decisions in assembly are two steps: set flags (cmp, test, or any arithmetic), then jump with a jcc instruction that reads them.
  • cmp a, b is a hidden a - b; test a, b is a hidden a & b. Both keep only the flags.
  • jl/jle/jg/jge are for signed values (SF and OF); jb/jbe/ja/jae are for unsigned values (CF and ZF); je/jne work for both.
  • Labels name positions; jmp always jumps, and the skip-the-else jump after an if block is a plain jmp.
  • Real jumps store a relative offset from the end of the instruction, which makes code position independent.
  • Keep the jcc directly after the flag-setting instruction, because the next arithmetic instruction overwrites the flags.

Next: turn jumps backwards to repeat work in Writing Loops.