How does the compiler translate an if-else statement to assembly?
It compiles to a compare, a conditional jump over the "then" block, and an unconditional jump over the "else" block — the machine-level equivalent of goto.
* The compiler's if/else skeleton: compare, conditionally jump past the then-block, then unconditionally jump past the else-block to a shared join label. *
There is no if in assembly; the compiler rewrites it as conditional branches. The pattern is always the same shape:
int absdiff(int x, int y) {
if (x > y) return x - y;
else return y - x;
}
absdiff:
cmpl %eax, %edx # compare x with y
jle .L6 # if x <= y, jump to the else part
subl %eax, %edx # then: x - y
movl %edx, %eax
jmp .L7 # skip over the else
.L6:
subl %edx, %eax # else: y - x
.L7:
ret
The recurring structure: compare → conditional jump past the "then" → "then" code → unconditional jump past the "else" → "else" code → join point. Once you recognize this skeleton, if-else statements jump out of disassembly immediately. (This is also why C's goto, though you should never write it, mirrors machine code so closely.)
Go deeper:
Conditional (Wikipedia) — the if-then-else construct the compiler lowers to branches.