A CPU cannot run C or Python directly. It runs machine instructions: very small steps such as "load this word from memory", "add two registers", "jump to that address if zero".
From source code to a running program
- Compile. A compiler (
gcc) translates each.cfile into machine code for one kind of CPU, checking types on the way. - Link. The linker joins your code with library code (
printflives in the C library) into one executable file. - Load and run. The operating system copies the program into memory, gives it a stack, and starts the CPU at
main.
Python works differently: an interpreter reads your program and carries out each line itself. StepVioz also interprets C, which is how it can watch every step and catch errors that compiled C hides.
The CPU's loop
The CPU repeats one cycle billions of times a second: fetch the next instruction from memory, decode it, execute it, and move on. A 3 GHz CPU runs about 3 billion cycles a second, and often more than one instruction per cycle. Its fastest storage is a few dozen registers; then caches, then RAM, which is about a hundred times slower than a register.
The call stack
#include <stdio.h>
int depth(int n) {
if (n == 0) return 0;
int below = depth(n - 1);
return below + 1;
}
int main(void) {
int d = depth(3);
printf("depth %d\n", d);
return 0;
}Each function call pushes a frame onto the stack: its parameters, its local variables and the place to return to. Watch the stack grow as depth calls itself, and shrink as each call returns, newest first. If the calls never stop, the stack runs out of room: a stack overflow.
Quick check
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.