1#include <iostream>2int area(int w, int h) {3 return w * h;4}5int main() {6 int a = area(3, 4); int a = area(3);7 int b = area(5, 2);8 std::cout << a + b << "\n";9}$ ./calc22$ g++ calc.cpp -o calcerror: line 6, area(3)# area takes 2 intsmain()a?b?area()w?h?3452121022!
Violet card: the source code (calc.cpp)Slate trays: stack frames, one per running call, with its local variables as boxesTokens: arguments hopping into a call, answers hopping back, a red ! for a compile errorOn the left: the source file calc.cpp, with the function area and main. On the right: the call stack, where main's frame holds a and b. At the back: the terminal. Each call to area puts a new frame for it on top of the stack. The arguments are copied into w and h, return sends the answer back to the calling line, and the frame comes off again. a gets 12, b gets 10, and the program prints 22. Calling area(3) with one argument is a compile error: no program is made. The drawing shows each call's local variables on a tray, its stack frame, and the trays pile up as the call stack. The C++ standard only says that local variables and parameters live until their block or call ends; real compilers keep them in a stack frame or in CPU registers.

Define

  1. A function is a named block of code. Line 2 reads: it returns an int, it is called area, and it takes two ints, w and h. These are its parameters. The body, line 3, runs only when area is called.

First call

Second call

Results and rules

What happens

;; step 1/10 · define
int    area   (int w, int h)   {
↑      ↑       ↑
return name    parameters: a type and a name each
type

3    return w * h;   the body: runs only when called
area sits above main: a function must be declared
before the line that calls it

The drawing shows each call's local variables on a tray, its stack frame, and the trays pile up as the call stack. The C++ standard only says that local variables and parameters live until their block or call ends; real compilers keep them in a stack frame or in CPU registers. int parameters are passed by value: the parameter is a new variable initialized with a copy of the argument. In void twice(int x) { x = x * 2; }, calling twice(n) leaves n unchanged. A later lesson shows references, which let a function change the caller's variable.