Storage of local variables
What you'll learn: How the computer uses the call stack to give each function its own private workspace for variables.
The cafeteria tray analogy
Imagine a stack of cafeteria trays. When you call a function, it’s like placing a new tray on top of the stack. This tray contains everything that specific function needs to do its job—specifically, its local variables.
In C, this stack of "trays" is called the Call Stack. Each tray is technically known as a Stack Frame. When a function starts, its frame is pushed onto the top. When the function finishes, its frame is popped off and discarded.
Private workspaces
Because every function gets its own frame, local variables are completely private. If main() has a variable named x and it calls calculate(), which also has a variable named x, they do not clash. They live on different "trays."
The computer only ever looks at the tray on the very top of the stack. This is why a function cannot accidentally mess with the variables of the function that called it.
#include <stdio.h>
void bake_cake() {
int temperature = 350; // Stored in bake_cake's stack frame
printf("Baking at %d degrees.\n", temperature);
} // bake_cake's frame is destroyed here
int main() {
int temperature = 70; // Stored in main's stack frame
bake_cake();
// Even though bake_cake changed its own 'temperature',
// main's 'temperature' remains 70.
printf("Room temperature is %d.\n", temperature);
return 0;
}
Why this matters
This system is the reason recursion works and why your programs don't collapse into a mess of conflicting names. When bake_cake finishes, the memory it used for temperature is instantly freed up for the next function call.
The stack is fast and automatic, but it is temporary. Once that "tray" is removed from the stack, any data stored inside it is gone forever. This is why local variables don't persist after a function returns—their "home" has been cleared away to make room for the next task.
Key takeaway
Local variables live in temporary "stack frames" that are created when a function is called and destroyed as soon as it returns.