Loading lessons...
Static Local Variables
Static Local Variables
Normally a local variable is created each call and destroyed at the end. A static local is different: it keeps its value between calls.
The magic keyword
Add static to a local declaration:
int nextId() {
static int id = 0; // created once, keeps its value
id = id + 1;
return id;
}
Each call to nextId returns a bigger number: 1, 2, 3, ... The variable id is initialized only once - the first time the function runs - and then survives for the rest of the program.
How it differs from a normal local
void counter() {
int normal = 0; // reset to 0 on every call
static int keep = 0; // initialized once, then kept
normal = normal + 1;
keep = keep + 1;
cout << normal << " " << keep << endl;
}
Every call prints 1 for normal, but keep grows: 1, 2, 3, ...
When to use static locals
- Counting across calls: total invocations, running IDs, cached values.
- Lazy initialization: a resource (like a big table) built the first time it's needed and reused after.
- Simple, single-instance state that shouldn't be a global.
int getCount() {
static int count = 0;
count = count + 1;
return count;
}
Keep it simple
Static locals are handy but easy to overuse. They make a function stateful: calling it twice can give different results. Use them when the state is genuinely meant to persist - not just to avoid a global.
TL;DR
static int count = 0;inside a function is created once.- It keeps its value between calls;
count = 0runs only the first time. - Great for counters, IDs, and lazily built one-time resources.
- The initializer runs on the first call, not on every call.
- Don't overuse them - they make functions stateful.