What is the difference between an unconditional branch and a conditional branch, and how is a branch implemented at the hardware level?
An unconditional branch always jumps; a conditional branch jumps only when a tested condition holds.
* Both branch kinds set PC, but a conditional branch falls through when the tested condition is false. *
Assembly has no if or goto keyword — control flow exists only as branch instructions that change where the processor reads its next instruction. Mechanically, a branch just sets the program counter (PC) to the target's address: PC = &label. The CPU then fetches from there instead of the next sequential instruction.
| Type | x86 syntax | Behavior |
|---|---|---|
| Unconditional | jmp .L7 |
Always continues at .L7 |
| Conditional | jl .L2 |
Continues at .L2 only if the "less-than" condition is true, else falls through |
subl %eax, %edx
movl %edx, %eax
jmp .L7 # always taken
...
.L7:
...
A high-level goto label maps directly onto jmp label. Every loop, if, and switch you write in C is ultimately built out of these two primitives.
Go deeper:
Program counter (Wikipedia) — the program counter a branch overwrites.
Control flow (Wikipedia) — how branches assemble into control flow.
Jcc — x86 conditional-jump reference — the x86 conditional-jump family.