What exactly happens inside the CPU when one line of your code runs? A CPU is less a clever machine than a remote control with a handful of buttons, so one line becomes several presses.
A computer is, in the end, a very fast calculator. Your code becomes a list of extremely simple instructions, and the CPU runs them one at a time from the top. This chapter shows what "one at a time" actually looks like, what gets recorded where when you call a function, and where data lives in memory. Step through the animation as you read.
It fetches the next instruction from memory, decodes what it means, and executes it — billions of times per second. "A program running" is just this loop repeating quickly.
Memory is a long row of one-byte cells, each with a number called its address. The CPU only ever says "load the value at address N" or "store this at address N". Variable names are conveniences that compile down to addresses.
Memory is far away by CPU standards (tens to hundreds of times slower), so the CPU keeps a handful of values in ultra-fast storage called registers. One special register, the PC (program counter), holds the address of the next instruction — watch it in the right-hand panel and you can see exactly where execution flows.
Calling a function needs somewhere to keep its local variables: a stack frame, pushed on call and popped on return (last in, first out — hence "stack"). Crucially, the frame holds more than locals: it also records the address to come back to. That is how return knows where to go.
Arrays and objects that are large, or must outlive the call that made them, cannot live in a frame that disappears. They go on the heap, and the stack keeps only their location. Here each heap box gets a tag (@1, @2…) and stack variables hold just that tag — check that the @1 on the stack matches the @1 on the box.
1main() {2 prices = [12000, 8000]PC ◀3 total = sum(prices)4 print(total)5}6sum(list) {7 t = 08 for n in list: t += n9 return t10}
Execution starts at main's first line — sum below (lines 6–10) is only a definition. The CPU keeps "the line to execute" in the PC register: PC = 2. The array itself lives in a heap box tagged @1; prices stores only that number.
Try it in the simulator
Terms in this chapter
A call = register the return address + jump. Return = jump back to it.
The remaining problem
But who cleans up those heap boxes, and when? Why does memory fill up as a program keeps running? →