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; lea leaves flags unchanged.
cmpq %rsi, %rdi          # flags from rdi - rsi; operands unchanged
testq %rax, %rax         # flags from rax & rax; test zero/sign

After comparing a - b, choose the correct condition:

RelationSigned conditionUnsigned condition
a == b / a != be / ne (ZF / !ZF)Same
a < bl (SF != OF)b (CF)
a <= ble (ZF or SF != OF)be (CF or ZF)
a > bg (!ZF and SF == OF)a (!CF and !ZF)
a >= bge (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 result

In 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 compact function 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 div111 source 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 with cmp $555, then uses pivots including 222 and 888; some leaves use sete or cmove. The pivot need not match the slide’s 444.