Quiz Entry - updated: 2026.07.10
How is a for loop translated to assembly?
A for is rewritten as a while (init; while(test){ body; update }), which is then rewritten as a guarded do-while — so it collapses into the same body + conditional-jump-back pattern.
* for rewrites into a guarded do-while — every loop kind compiles to the same shape. *
The transformation chain a compiler walks:
for (Init; Test; Update) { Body }
↓ (for → while)
Init; while (Test) { Body; Update; }
↓ (while → guarded do-while)
Init;
if (!Test) goto done;
loop:
Body
Update
if (Test) goto loop;
done:
Assembly (a typical for (i=0; i<n; i++)):
movl $0, %eax # Init: i = 0
.L_loop:
# Body
addl $1, %eax # Update: i++
cmpl %edi, %eax # Test: i < n ?
jl .L_loop # repeat while true
.L_done:
Why this matters for reverse engineering: Since all three loop kinds funnel into the same machine shape, you can't always tell from disassembly whether the original C was a for, while, or do-while — they look the same once compiled. You read the structure (init, body, update, back-edge), not the original keyword.
Go deeper:
For loop (Wikipedia) — the three-part for loop.
Compiler Explorer (godbolt) — watch for → while → do-while in real compiler output.