Sub topic 11
Function Calls and the Call Stack
This chapter assumes that you know basic C syntax, variables, operators, control flow, functions, and how to compile a small C program.
When a C program calls a function, the program must remember where to return, which arguments were passed, and which local variables belong to that call. It stores this information in a stack frame. The collection of active stack frames is called the call stack.
The stack follows last in, first out (LIFO) order. The most recent function call is the first one to finish.
What a stack frame contains
A frame usually contains:
- The function's parameters.
- Its local variables.
- The return address, which tells the program where to continue.
- Temporary values needed while the function runs.
The exact layout is implementation-dependent, but this model is useful for tracing programs.
| Event | Call stack effect |
|---|---|
| `main` starts | A frame for `main` is created |
| `add` is called | An `add` frame is placed above `main` |
| `add` returns | The `add` frame is removed |
| The program ends | The `main` frame is removed |
A function call step by step
#include <stdio.h>
int add(int x, int y) {
int result = x + y;
return result;
}
int main(void) {
int answer = add(3, 4);
printf("%d\n", answer);
return 0;
}The execution proceeds as follows:
- The program creates a frame for
main. maincreatesanswer, then callsadd(3, 4).- A new frame for
addis created. Its parameters arex = 3andy = 4. addcreatesresultand stores7in it.addreturns7. Its frame is removed.mainstores the returned value inanswerand prints7.
The parameter x is a copy of the argument value. Changing x inside add does not change the original expression or variable in the caller.
A function's automatic local variables normally exist only while that function's frame is active. After the function returns, those variables no longer have a valid lifetime.
Tracing nested calls
For nested calls such as main calling first, which calls second, write the frames from bottom to top:
mainfirstsecond
When second returns, remove only second. Then first resumes. This method prevents mixing values from different calls.
The call stack also explains recursion. Each recursive call creates a separate frame, even though all calls execute the same function. The frames are removed in reverse order when the base case returns.
Exercise
In the program above, where does execution continue after add returns, and what value does answer receive?
Show answer
Execution continues at the statement in main after the call expression. The returned value 7 is assigned to answer.