C vs Assembly
Early operating systems were often written in assembly, one line per machine instruction, for one specific processor. When UNIX was rewritten in C in 1973, it became possible to move the whole system to new machines by building it again rather than rewriting it. That move is the whole story of C versus assembly.
The rule
Assembly speaks one chip's language; C lets a compiler translate for any chip.
Assembly is a readable spelling of a processor's own instructions. Each processor family has its own instruction set, so assembly written for an ARM chip means nothing to an x86-64 chip or a RISC-V chip.
C describes what you want. A compiler for the target processor decides which instructions do it. Take one line from our logger:
total = total + reading;For a 32-bit ARM chip, a compiler might produce something like this (the exact output depends on the compiler and its settings):
ldr r0, [sp, #4] @ load total from memory
ldr r1, [sp, #8] @ load reading
add r0, r0, r1 @ add them
str r0, [sp, #4] @ store the new totalA compiler for x86-64 would produce different instructions from the same line. With optimisation turned on, it might keep total in a register and skip the loads and stores entirely.
| Assembly | C | |
|---|---|---|
| Runs on | One processor family | Any processor with a C compiler |
| One line means | One instruction | Zero or more instructions |
| Who picks registers | You | The compiler |
| Control | Total | Nearly total |
Assembly has not disappeared. It still appears in the first instructions a device runs at power-on, in special instructions C has no words for (such as switching interrupts off), and in a few hand-tuned inner loops. Even then it is usually a small piece inside a C project, and most compilers offer an extension for embedding a few lines of it.
You can watch the translation yourself: gcc -S logger.c stops after compiling and writes the assembly to logger.s.
The shortcut
Ask one question of each piece of code: "Does this need a specific instruction on a specific chip?" If yes, write that small piece in assembly. If no, write it in C and let the compiler choose.
The new board
The greenhouse project switches from an ARM board to a RISC-V board.
Drills
Answer fast — trust the rule.
The logger was written in C for ARM. What is usually needed to run it on an x86-64 machine?
Which GCC flag stops after compiling and writes the assembly to a .s file?
Which task is most likely to still need a few lines of assembly?
How many machine instructions does one C statement become?
Remember
- Assembly speaks one chip's language; C lets a compiler translate for any chip.
- Shortcut: "does this need a specific instruction on a specific chip?" Only then reach for assembly, and keep it small.
- Trap: assuming a C line maps to one fixed set of instructions. The compiler and its settings decide.
