Theory
Extra: how does the CPU see it?
Extra. Not graded. How does the processor run if, loops and switch?
Open the tool window's Assembly tab (topic 2's extra step explains how to read it). On the left is your practice/03/main.c.
Jumps instead of blocks
The processor has no if and no while. It has two commands:
cmp a, bcompares two numbers and remembers the result;- a jump: "carry on not with the next line but at this label".
jmpalways jumps, whilejl,jle,jg,jge,je,jneonly jump when the last comparison was <, ≤, >, ≥, =, ≠ respectively.
Labels such as .L18: are places to jump to.
What to notice (-O0)
if (grade < lowest)becomescmpandjge: a jump over the assignment when the condition is not met. The compiler turns the condition around: it has to jump whenlowest = grade;must not run.- The
forloop: the assignmenti = 1, a jump down to the condition, and the condition (cmpandjleback up) sits after the loop body.i++is theadd ..., 1just before the condition. grade < 5becomescmp ..., 4andjg: for integers, "< 5" is the same as "≤ 4".- The
switchbecomes a jump table: 5 is subtracted fromgrade, and the number 0–5 picks one of six addresses in the table. One check instead of six comparisons.
Switch to -O1: i, sum, lowest and the rest live in registers, so the loop is shorter and the order of the C lines mixes in the instructions.