Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 40 ยท Control Flow

How if, switch and Ternaries Compile

See how compilers turn if/else, switch and the ternary operator into compare-and-jump code, jump tables and branchless CMOV, and why branch prediction matters.

You write if, switch and a ? b : c as three different constructs, but the CPU sees only compares, jumps and a few conditional moves. A compiler chooses which of several machine-code layouts to use, and that choice affects speed, sometimes by a lot. In this lesson you learn the usual layouts, how a switch becomes a table of addresses, what cmov does to remove a branch, and why a branch that is hard to predict can slow a loop to a crawl.

You need the pattern from Compare and Jump and the loop shapes from Writing Loops. The real compiler output below is shown read-only and is typical of GCC at -O2 for x86-64; your compiler, version and flags may produce different but equivalent instructions. The runnable parts use the toy CPU, with its interpreter at the bottom of each TryIt.

if and else: invert, then fall through

For this C code:

C
if (a > b) {
    result = 1;
} else {
    result = 2;
}

a compiler usually inverts the condition. It jumps over the then-block when the condition is false, so the then-block can simply follow the compare:

NASM
        cmp   edi, esi          ; a ? b
        jle   .Lelse            ; condition inverted: a <= b skips the then-block
        mov   eax, 1            ; then-block
        jmp   .Lend             ; skip the else-block
.Lelse:
        mov   eax, 2            ; else-block
.Lend:
flowchart TD
  A["cmp a, b"] --> B{"jle .Lelse<br/>(a <= b ?)"}
  B -- "no: fall through" --> C["then-block"]
  C --> D["jmp .Lend"]
  B -- "yes: jump" --> E["else-block"]
  D --> F[".Lend"]
  E --> F

The condition is inverted so the "true" path falls straight through; only the false path takes a jump.

An if without else is the same picture without the second block. && and || become short-circuit jumps: for a > 0 && b > 0 the code tests a, jumps past everything if it fails, and only then tests b. This is why C guarantees that the right side is not evaluated when the left side already decides the result.

switch: a chain or a table

A switch with a few cases compiles into a chain of cmp and je, like several ifs in a row. With many consecutive case values, a compiler builds a jump table: an array of code addresses stored in the program's read-only data, indexed by the switch value. One bounds check, one indexed load and one indirect jump replace the whole chain, so the cost does not depend on which case runs.

NASM
        cmp   edi, 3
        ja    .Ldefault               ; unsigned compare: also catches negative values
        mov   edi, edi                ; zero-extend into rdi
        jmp   [QWORD PTR .Ltable[rdi*8]]   ; indirect jump through the table (simplified)

The unsigned ja is a neat trick. A negative value, read as unsigned, is huge, so the single comparison rejects both "too big" and "negative" at once. In position-independent builds the table usually stores 32-bit offsets relative to the table instead of absolute addresses, so the sequence has a few more instructions, but the idea is the same.

flowchart LR
  A["value"] --> B{"value > max<br/>(unsigned)?"}
  B -- "yes" --> D["default"]
  B -- "no" --> C["table[value]"]
  C --> E["indirect jump to case"]

One range check, one table lookup, one indirect jump: the cost is the same for every case.

The toy CPU has a register-indirect jump (jmpr) and can preload memory with label addresses (the data option), so we can build both versions and compare the instructions they execute.

JS A switch as a jump table versus a compare chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The table version always costs 10 steps for a real case and 5 for the default, independent of the value. The chain grows as you move through the cases: case 0 needs only a few steps, case 3 needs more, and the default must fail every test first. With four cases the difference is small, which is why compilers keep short switches as chains. With forty cases, the table wins clearly.

Branchless selection with cmov

Sometimes a compiler removes the branch altogether using a conditional move. cmovcc dest, src copies src into dest only if the condition holds; otherwise it does nothing. The condition codes are the same as for jumps (cmovl, cmovg, cmove, and so on). For a > b ? a : b GCC typically emits:

NASM
max:
        cmp     edi, esi
        mov     eax, esi          ; assume b
        cmovge  eax, edi          ; if a >= b, take a instead
        ret

And for x < 0 ? 0 : x a typical result is:

NASM
clamp_low:
        xor     eax, eax          ; eax = 0
        test    edi, edi
        cmovns  eax, edi          ; if x is not negative, eax = x
        ret

There is no jump at all, so execution time does not depend on the data. The toy version below runs both the branching and the cmov form of "maximum" for two different inputs.

JS Branch versus cmov: the same answer, a different path

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The step counts are close, and that is the honest lesson: on the toy, the branchless form saves only a jump. The real gain on a modern CPU is not the instruction count but avoiding a wrong guess, which the next section shows. cmov is not always better, though. It must compute both possible values first, it creates a data dependency on the compare, and when the branch is predictable a real branch is often faster. Compilers weigh this, and they will not use cmov when one side has a side effect (a function call or a memory write) or could fault.

Why branches can be slow: prediction

A modern CPU works like an assembly line: while one instruction executes, the next ones are already being fetched and decoded. When it meets a conditional jump, it does not wait for the compare; it guesses the outcome and continues down the guessed path. A correct guess costs almost nothing. A wrong guess means throwing away the work done on the wrong path (typically on the order of 15 or more cycles on current desktop and server cores).

The simplest predictor keeps a small saturating counter per branch: taken branches push it up, not-taken branches push it down, and the top half means "predict taken". Real predictors are far more sophisticated (they use history patterns), but this toy model already shows the effect. The program counts wrong guesses for the branch if (x >= 128) over 2,000 byte values, once in random order and once sorted.

JS A 2-bit predictor on random versus sorted data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In random order the branch is a coin flip and about half the guesses are wrong (here 992). In sorted order the branch goes the same way for a long stretch, then flips once, so almost every guess is right (here 3 misses). This is the well-known reason why the same loop can run much faster over sorted data, and why compilers sometimes prefer cmov for unpredictable conditions. It is only a model: it shows the direction of the effect, not real cycle counts. You will measure the effect more carefully in Performance: Pipelines, Caches and Branches.

Do not rewrite your C code to avoid branches by hand. Compilers already choose cmov or a branch based on heuristics, and a profile of real data beats guessing. Reading the output, as you can do with gcc -O2 -S, tells you which one you got.

Ternary operators and logic expressions

A ternary c ? x : y is an if/else that produces a value, so it compiles by the same rules: a branch when the arms are costly, cmov when both are cheap constants or registers. Boolean expressions such as return a > b; often need no jump at all: the compiler uses cmp followed by setg al, which stores 0 or 1 straight from a flag. Knowing these shapes makes unfamiliar disassembly much less intimidating.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a compiler usually invert the condition of an if statement when it emits the jump?

    Jumping over the then-block when the condition fails lets the common layout be: compare, jump over, then-block, with the then-block following the compare directly.
  2. 2. A switch is compiled to a jump table. Which instruction pair does the dispatch rely on?

    One unsigned compare rejects out-of-range and negative values, then the code loads a target address from the table and jumps to it, regardless of which case it is.
  3. 3. What does cmovg rcx, rax do?

    cmovcc is a conditional move: it reads the flags and either copies the source or leaves the destination unchanged. It never changes the instruction pointer.
  4. 4. In the predictor experiment, why are the sorted data so much easier on the predictor than random data?

    A branch whose outcome repeats is trivial to predict. A random outcome is a coin flip, so about half the guesses are wrong, and each wrong guess wastes pipeline work.
  5. 5. When is a real branch often better than cmov?

    A well-predicted branch is nearly free and skips work on the not-taken side, while cmov always computes both sides. For unpredictable conditions, cmov usually wins.

Summary

  • A compiler lays out if/else by inverting the condition so the likely block falls through, with a jmp skipping the other block.
  • && and || become short-circuit jumps; ternaries follow the same rules as if/else.
  • A switch with many dense cases becomes a bounds check (one unsigned compare) plus an indirect jump through a table of addresses, so every case costs the same.
  • cmovcc copies a value only if the condition holds, giving branchless code whose timing does not depend on the data.
  • Wrong branch predictions cost many cycles; unpredictable branches are good candidates for cmov, predictable ones are not.
  • The assembly you see differs between compilers and flags, so treat any listing as typical, not universal.

Next: the memory structure behind every function call in The Stack: push, pop and rsp.