13.5 — if statements and loops in assembly
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 retcmp ..., 0comparesxwith 0.jns .L2= "jump if not signed (not negative)" to.L2.- If we didn't jump,
xis negative: return 0, thenjmp .L3to the end. - At
.L2: returnx.
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 retcmovns = "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 .L1test edi, edi/jle .L4: ifn <= 0, skip the loop and return 0.eaxisi(starts at 1),edxistotal(starts at 0)..L3is the loop body:total += i,++i, thenjne .L3jumps back up whilei != 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.
Tip: press ← / → to move between lessons, / to search.