Jumps, flags and loops

There is no if and no while — only a comparison that sets flags, and a jump that reads them.

What you'll learn
  • Explain what cmp computes and which flags it sets
  • Choose between signed (jl, jg) and unsigned (jb, ja) jumps
  • Build a loop from dec, cmp and a conditional jump

The CPU runs instructions in order until something changes eip, the instruction pointer. A jump does exactly that. jmp label always jumps; a conditional jump such as jl jumps only if the flags say so.

_start:
    mov ecx, 101
    mov ebx, 42     ; exit status is 42
    mov eax, 1      ; sys_exit
    cmp ecx, 100    ; compare ecx to 100
    jl skip         ; jump if less than
    mov ebx, 13     ; exit status is 13
skip:
    int 0x80

The program exits with 13, not 42: 101 is not less than 100, so jl falls through and mov ebx, 13 runs. The comment on the second line describes the other branch. Drag the slider to start ecx below 100 and the jump is taken.

03_jump.asm. cmp sets the flags shown under the registers; jl reads them. Change the starting value of ecx to watch the branch flip.

What cmp really does

cmp a, b computes \(a - b\), throws the result away, and keeps four flags: ZF (the result was zero), SF (its sign bit was set), CF (the subtraction needed a borrow — unsigned \(a < b\)) and OF (signed overflow). Every conditional jump is a test on those bits. That is why there are two families: jl/jg treat the registers as signed numbers, jb/ja as unsigned. The bit pattern 0xffffffff is −1 to one and 4,294,967,295 to the other.

cmp on seven pairs, including this course's own and the cases where signed and unsigned comparisons disagree. Each was checked against the real CPU's flags.

The last example is the subtle one: \(-2^{31} - 1\) overflows to \(2^{31} - 1\), a positive number, so SF is 0. A test on SF alone would wrongly say “not less”. jl tests SF ≠ OF, and OF = 1 corrects for the overflow.

A loop

04_jump1.asm doubles ebx four times:

    mov ebx, 1
    mov ecx, 4      ; number of iterations
label:
    add ebx, ebx
    dec ecx
    cmp ecx, 0
    jg label

and exits with \(2^4 = 16\). The cmp ecx, 0 is not even needed: dec already sets ZF and SF from its result, so jg label could follow it directly — which is how compilers write such loops.

04_jump1.asm: add, dec, cmp, jg, around and around. Change the iteration count; the exit status is 2 to that power (up to 2^7 = 128 here, since only one byte survives).

Try it yourself. In 04_jump1.asm, remove cmp ecx, 0 and confirm the exit status is still 16. Then start ecx at 0 instead of 4: how many times does the loop run before jg fails, and what does echo $? show? Finally, change jl to jb in 03_jump.asm and find a starting ecx where the two disagree.

View source on GitHub →