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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <stdio.h>

int global_calls = 0; /* visible throughout the program */

void increment(void) {
    static int calls = 0; /* initialized only once to 0 */
    calls++;
    global_calls++;
    printf("static local=%d  global=%d\n", calls, global_calls);
}

int main(void) {
    increment();
    increment();
    increment();
    return 0;
}

Expected output

1
2
3
static local=1  global=1
static local=2  global=2
static local=3  global=3

Common mistakes

  • Thinking static int x = 0 resets to 0 on every call: initialization happens only once, at program startup.
  • Confusing a local static with file-scope static: same keyword, different effects depending on context.
  • Using a static variable in a function as non-reentrant state: if two threads call the function simultaneously, there is a data race.
  • Not initializing a static variable explicitly: C zero-initializes static variables 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.

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.