Lesson 14 / 36
Scope & Storage
Where a variable lives and how long it survives.
Local vs global
A local variable is declared inside a function and only exists while that function runs. A global variable is declared outside every function and is visible everywhere in the file.
static keeps its value
A static local variable is initialised once and remembers its value between calls, unlike a normal local variable.
void counter(void) {
static int count = 0;
count++;
printf("%d\n", count);
}
// counter(); counter(); counter();
// prints 1, 2, 3
Output:
1 2 3
Quick check: What happens to a normal (non-static) local variable when its function returns?
- It keeps its value for next call
- It is destroyed
- It becomes global
Answer
It is destroyed — Local variables live on the stack and are freed once the function returns.