Quiz Entry - updated: 2026.07.10
How does a compiler translate an if-else statement into assembly?
It inverts the condition and uses jumps to skip past whichever block shouldn't run, so the two branches become labeled code regions.
* if-else: invert the condition, jump to skip the else, and let the expected then case fall through. *
There is no if in assembly, so the compiler first rewrites the C into an equivalent goto form, then emits jumps for the gotos.
C code:
if (a >= b) res = foo(a, b);
else res = bar(b, a);
Goto version (condition inverted):
if (a < b) goto L_false; // jump to else when the "if" is false
res = foo(a, b);
goto Exit;
L_false:
res = bar(b, a);
Exit:
return res * 2;
Assembly pattern:
cmpq %rsi, %r8 # compare a, b
jl .L_false # inverted: a < b -> take else branch
# ... then-branch (foo) ...
jmp .L_exit
.L_false:
# ... else-branch (bar) ...
.L_exit:
ret
Key insight: Inverting the test puts the "then" case as the fall-through (no jump taken). On most CPUs the not-taken path is the cheaper, better-predicted one, so compilers arrange the expected case to fall through.
Go deeper:
Control flow (Wikipedia) — how compares and jumps synthesise control flow.
Jcc — x86 conditional-jump reference — the conditional jump the compiler emits.