BETA Try the new lesson view
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, b compares two numbers and remembers the result;
  • a jump: "carry on not with the next line but at this label". jmp always jumps, while jl, jle, jg, jge, je, jne only jump when the last comparison was <, ≤, >, ≥, =, ≠ respectively.

Labels such as .L18: are places to jump to.

What to notice (-O0)

  • if (grade < lowest) becomes cmp and jge: a jump over the assignment when the condition is not met. The compiler turns the condition around: it has to jump when lowest = grade; must not run.
  • The for loop: the assignment i = 1, a jump down to the condition, and the condition (cmp and jle back up) sits after the loop body. i++ is the add ..., 1 just before the condition.
  • grade < 5 becomes cmp ..., 4 and jg: for integers, "< 5" is the same as "≤ 4".
  • The switch becomes a jump table: 5 is subtracted from grade, 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.