- How a
staticlocal variable retains its value between function calls - How to use a static counter to generate unique sequential IDs
- Why this pattern is thread-unsafe (and how to fix it)
- The difference between
staticlocal andstaticglobal variables - Real-world use cases: logging, session IDs, auto-increment counters
Why Static Variables for IDs?
In many programs you need a simple way to generate unique identifiers: log entry numbers, order IDs, session tokens, or simply a counter that keeps incrementing no matter how many times a function is called. A plain auto local variable is recreated on every call and loses its value the moment the function returns. A static local variable, however, is created once and keeps its value for the entire life of the program.
That's the key insight: a static local variable inside a function is the cleanest way to maintain state across calls without exposing that state to the rest of the program. No global variable needed, no risk of accidental modification from other functions, and the name stays private to the function that owns it.
💡 In one line: A static local is a variable that remembers. Perfect for counters, ID generators, and one-time initializations.
What Makes static Special
| Property | Behaviour |
|---|---|
| Storage duration | Static — lives for the whole program run |
| Scope | Block scope — visible only inside the function that declares it |
| Initial value | Automatically zero-initialized if not explicitly set |
| Initialization timing | Once, before the first call to the function |
| Thread safety | Not thread-safe — concurrent calls will race on the counter |
Complete C Program
Program: Generate unique sequential IDs using a static counter
#include <stdio.h>
/* Returns the next unique ID every time it is called */
int next_id(void) {
static int counter = 0; /* created once, initialized to 0 */
counter++; /* remembered across calls */
return counter;
}
/* A second, independent generator — its static counter is separate */
int next_batch_id(void) {
static int batch = 1000;
return batch++;
}
int main(void) {
int i;
printf("--- Generating 5 unique IDs ---\n");
for (i = 0; i < 5; i++) {
printf("next_id() = %d\n", next_id());
}
printf("\n--- Generating 3 batch IDs (independent counter) ---\n");
for (i = 0; i < 3; i++) {
printf("next_batch_id() = %d\n", next_batch_id());
}
printf("\n--- Calling next_id() again after other work ---\n");
printf("next_id() = %d\n", next_id());
return 0;
}
Program Output
--- Generating 5 unique IDs ---
next_id() = 1
next_id() = 2
next_id() = 3
next_id() = 4
next_id() = 5
--- Generating 3 batch IDs (independent counter) ---
next_batch_id() = 1000
next_batch_id() = 1001
next_batch_id() = 1002
--- Calling next_id() again after other work ---
next_id() = 6
Notice that next_id() returned 6 at the end, even though other functions were called in between. The static variable counter kept its value. Meanwhile next_batch_id() maintained its own independent counter starting at 1000 — the two statics are completely separate.
Step-by-Step Explanation
Let's break down exactly what happens on every call.
1. The static variable is created once:
static int counter = 0;
The static keyword tells the compiler: allocate this variable in the program's static data area, not on the stack. The = 0 initialization runs only once — before main() starts — not on every call. If you wrote static int counter; without an initializer, it would still be zero, because all static-storage variables are zero-initialized by the C standard.
2. The increment persists:
counter++;
return counter;
Each call increments the same memory location. First call: 0 → 1, returns 1. Second call: 1 → 2, returns 2. And so on. This is the mechanism behind auto-increment IDs, which you'll see in databases, log files, and message queues.
3. Scope is still limited:
Despite living for the whole program, counter is not visible outside next_id(). Try to write counter = 99; in main() and you'll get a compile error. This is a huge advantage over a global variable: the state is encapsulated where it belongs.
4. Each function gets its own static:
next_batch_id() declares its own static int batch = 1000;. This is a completely separate memory location from counter. There's no collision, no sharing. Each static belongs to its enclosing function.
5. The state survives the whole program:
After the loops finish, we call next_id() once more and get 6. The value 5 was stored in the static area and stayed there. This is why static variables are ideal for: log sequence numbers, session counters, one-time setup flags, and any state you need to remember but keep private.
6. The thread-safety caveat:
If two threads call next_id() at the same time, the read-increment-write sequence can interleave, producing duplicate IDs. Fix it with a mutex (pthread_mutex_lock on POSIX, InitializeCriticalSection on Windows) or use an atomic integer (stdatomic.h in C11). For single-threaded programs — the common case in simple C exercises — the plain static counter is perfectly fine.
🎯 Remember this: A static local variable is the standard C idiom for "state that outlives its function but doesn't leak into the rest of the program." Use it whenever you need an auto-increment counter, a one-time flag, or a persistent cache — and remember to protect it with a lock if multi-threading is in play.
Frequently Asked Questions
1. Can I reset the static counter back to zero?
Not from outside the function — that's the whole point of encapsulation. If you need a reset, expose a companion function like void reset_id(void) { /* reset internal static */ }. But you can't access the static directly. If external control is required, a global variable is the more appropriate choice.
2. What's the difference between a static local and a static global?
A static local lives inside a function; its scope is limited to that function but its lifetime is the whole program. A static global (file-scope static) is visible throughout the file it's declared in, but not outside it — it's used to give a variable internal linkage. Both have static storage duration; the difference is visibility.
3. Is the initializer really run only once?
Yes. The C standard guarantees that a static local's initializer runs before main() begins (or at least before the first call to the function, depending on the exact wording), and never again. In practice, the compiler places the initialized value directly in the program's data section at load time — no runtime work at all for a constant initializer.
4. Can static locals be initialized with a non-constant expression?
In C, no — the initializer must be a constant expression. In C++, you can use non-constant initializers (they run the first time the function is called). This is a notable difference between the two languages and catches people who move code between them.
5. Do static variables work inside recursive functions?
Yes, but be careful: a static local is shared across all recursive calls of the same function. If you use one as a "depth counter," every frame sees the same value — which is often useful, but sometimes surprising. If you need a per-frame variable, use an ordinary automatic local; if you need to count total invocations across all recursion levels, use a static.
6. Can I use a static counter to generate unique IDs in a multi-threaded program?
Only if you protect it. Wrap the increment in a mutex or use C11 atomics (atomic_int and atomic_fetch_add). Without protection, two threads can read the same value before either writes, producing duplicate IDs — a classic data race. The C standard says concurrent modification of a non-atomic static is undefined behaviour.
💡 Tip: For a truly robust ID generator, combine the static counter with a time-based component (e.g., time(NULL) or clock_gettime) and a process ID, so IDs remain unique across program restarts. Just the static counter alone resets every time the program starts.