Static variables in C: solved exercise
Static variables in C: solved exercise
If you searched for a solved static variables exercise in C, here is the key pattern: a static local variable retains its value between function calls, unlike a regular local variable which is re-initialized on every call.
static has two uses in C. Inside a function: the variable persists in memory for the entire lifetime of the program. At file scope: it restricts the symbol’s visibility to the current translation unit (internal linkage).
Problem statement
Implement an increment() function that tracks internally how many times it has been called, without using any global variable. Call it three times from main and also print a global counter to compare both approaches.
C solution
Expected output
Common mistakes
- Thinking
static int x = 0resets to 0 on every call: initialization happens only once, at program startup. - Confusing a local
staticwith file-scopestatic: same keyword, different effects depending on context. - Using a
staticvariable in a function as non-reentrant state: if two threads call the function simultaneously, there is a data race. - Not initializing a
staticvariable explicitly: C zero-initializesstaticvariables automatically, but being explicit is good practice.
Practical use
Local static variables are used in call counters, unique ID generators, cached computed values, and simplified singleton patterns in C. File-scope static is key for module encapsulation in C projects without classes.
Recommended next exercise
- Functions in C: solved exercises
- Const in C: solved exercise
- Arrays as parameters in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
When is a local static variable initialized?
Only once, before the first execution of the program (or on the first pass through the declaration, depending on the compiler and standard). The default initial value is 0 if none is specified. After that it retains its value between calls.
What is the difference between a local static variable and a global variable?
Both persist in memory for the entire program. The difference is scope: a local static is only visible inside its function; a global is visible throughout the file (or the entire program if not static).
Are static variables safe in multithreaded programs?
Not necessarily. If two threads call the same function simultaneously, the static variable is shared and can cause a data race. In multithreaded code, prefer thread-local storage (_Thread_local in C11) or pass state as a parameter.