How Compilers Translate if, Loops and switch
A disassembly has no if, no for and no switch; it has comparisons, conditional jumps and labels. Recognising the handful of shapes compilers use for each statement is what lets you turn twenty lines of jumps back into three lines of C in your head, which is also what a decompiler does. This lesson collects those shapes from real GCC output. The assembly course's Jumps & Conditionals, Loops and Reading Compiler Output lessons write the same patterns by hand.
The shapes
| C | Typical compiled shape |
|---|---|
if (c) A; |
cmp/test, a jump on the opposite condition over A |
if (c) A; else B; |
jump to B on not-c; A; jmp past B; B |
x = c ? a : b; |
often no branch: cmov or setcc |
for/while |
the test at the bottom of the loop with a backward jump to the top, plus one test before entry ("loop inversion") |
do ... while |
body, test, backward jump |
dense switch |
bounds check, then an indirect jmp through a jump table of offsets in .rodata |
sparse switch |
a tree of comparisons (binary search on the case values) |
&&, || |
chains of jumps that skip the rest of the condition (short-circuit evaluation) |
The backward jump is the single most useful clue: a jump to a lower address is a loop.
Real output
The session compiles five small functions with GCC 13 at -O1 (readable but realistic) and prints the assembly without directives. The switch cases call external functions so the compiler can't turn them into a lookup table of constants.
cat > flow.c <<'SRC'
int classify(int x) {
if (x < 0) return -1;
else if (x == 0) return 0;
return 1;
}
int sum(const int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
int both(int a, int b) { return a > 0 && b > 0; }
int f0(int), f1(int), f2(int), f3(int), f4(int), f5(int);
int dense(int op, int x) {
switch (op) {
case 0: return f0(x); case 1: return f1(x); case 2: return f2(x);
case 3: return f3(x); case 4: return f4(x); case 5: return f5(x);
default: return -1;
}
}
int sparse(int code) {
switch (code) {
case 7: return 1; case 300: return 2; case 5000: return 3; case 90000: return 4;
default: return 0;
}
}
SRC
gcc -O1 -S -masm=intel -fno-asynchronous-unwind-tables -fcf-protection=none -o - flow.c \
| grep -vE '^\s*\.(file|text|p2align|globl|type|size|ident|section|align)|^\s*