Convention
Note that this course uses Unix AT&T syntax
Flags, comparisons, and branches
- ZF: zero result;
- SF: result’s sign bit;
- CF: unsigned carry/borrow;
- OF: signed overflow.
Flag effects depend on the instruction;
lealeaves flags unchanged.
cmpq %rsi, %rdi # flags from rdi - rsi; operands unchanged
testq %rax, %rax # flags from rax & rax; test zero/signAfter comparing a - b, choose the correct condition:
| Relation | Signed condition | Unsigned condition |
|---|---|---|
a == b / a != b | e / ne (ZF / !ZF) | Same |
a < b | l (SF != OF) | b (CF) |
a <= b | le (ZF or SF != OF) | be (CF or ZF) |
a > b | g (!ZF and SF == OF) | a (!CF and !ZF) |
a >= b | ge (SF == OF) | ae (!CF) |
j<condition> label branches; set<condition> byte writes 0 or 1; jmp label always jumps. js/jns test SF directly.
cmpl %esi, %edi # compare x with y
setg %al # signed x > y; writes only one byte
movzbl %al, %eax # zero-extend to a complete int resultIn the course’s Unix x86-64 examples, the first integer/pointer arguments use %rdi, %rsi, %rdx (32-bit views for int); results use %rax/%eax.
If else

optimization: (reduce branches)

while loop

for loop

general form

switch (compact)
often a jump-table is used, example:

Compilation verified on 2026-10-21
Local compiler: MSYS2 GCC 16.2.0, target
x86_64-w64-mingw32, default CPU tuning.A representative
compactfunction with the same case-to-destination grouping (1,2,3,5/6, default) and arithmetic bodies compiles to comparisons at-O0,-Og,-O1,-O2,-O3, and-Os. With-O2 --param=case-values-threshold=1, it generates a 7-entry jump table with the screenshot’s grouping, using 32-bit relative offsets. This demonstrates that the compiler’s heuristics matter even for dense cases.
switch (sparse)
example:

A direct-index jump table for 0..999 would need 1000 entries for only 10 case values (1% density). With 8-byte addresses that is 8000 bytes; with 4-byte relative offsets, 4000 bytes.
A linear chain of equality tests needs at most 10 case comparisons. A comparison tree reduces the search depth, typically toward for a balanced tree. Do not equate tree depth, cmp instructions, and conditional branches: one cmp can feed both je and jg/jl.
comparison-tree example (still a valid implementation):


Current compilation result
The exact
div111source from the screenshot was compiled with the GCC 16.2.0 environment above at-O0,-Og,-O1,-O2,-O3, and-Os: all use comparisons/branches, with no jump table. At-O2, the tree starts withcmp $555, then uses pivots including222and888; some leaves useseteorcmove. The pivot need not match the slide’s444.