13.5 — if statements and loops in assembly

📘 Chapter 13⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

if becomes compare + jump#

Assembly has no if. Instead it compares, then jumps (or not).

int clampToZero(int x){    if (x < 0)        return 0;    return x;}
Assembly (x86-64, GCC -O0)
clampToZero(int):        push    rbp        mov     rbp, rsp        mov     DWORD PTR [rbp-4], edi        cmp     DWORD PTR [rbp-4], 0        jns     .L2        mov     eax, 0        jmp     .L3.L2:        mov     eax, DWORD PTR [rbp-4].L3:        pop     rbp        ret
  • cmp ..., 0 compares x with 0.
  • jns .L2 = "jump if not signed (not negative)" to .L2.
  • If we didn't jump, x is negative: return 0, then jmp .L3 to the end.
  • At .L2: return x.
Tip

Labels like .L2 are places to jump to. Draw arrows from each jump to its label — it turns into a flowchart of your if.

Optimized: no jump at all#

int clampToZero(int x){    if (x < 0)        return 0;    return x;}
Assembly (x86-64, GCC -O1)
clampToZero(int):        test    edi, edi        mov     eax, 0        cmovns  eax, edi        ret

cmovns = "conditional move if not negative". The optimizer replaced the jump with a single smart instruction. Same result, faster.

Loops become jumps backwards#

int sumTo(int n){    int total = 0;    for (int i = 1; i <= n; ++i)        total += i;    return total;}
Assembly (x86-64, GCC -O1)
sumTo(int):        test    edi, edi        jle     .L4        add     edi, 1        mov     eax, 1        mov     edx, 0.L3:        add     edx, eax        add     eax, 1        cmp     eax, edi        jne     .L3.L1:        mov     eax, edx        ret.L4:        mov     edx, 0        jmp     .L1
  • test edi, edi / jle .L4: if n <= 0, skip the loop and return 0.
  • eax is i (starts at 1), edx is total (starts at 0).
  • .L3 is the loop body: total += i, ++i, then jne .L3 jumps back up while i != n + 1.
Key idea

A jump that goes backwards (to a label above it) is almost always a loop. Spotting these is one of the first RE skills.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.