A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A static local variable is declared inside a function but persists for the entire program lifetime. It is initialized once, on the first call. It retains its value across subsequent calls. It is visible only inside the function. It is the middle ground between local variables (reset every call) and global variables (visible everywhere). Use it for counters, caches, one-time initialization, and any state that belongs to a function but must survive between calls.
#include <stdio.h>int call_counter(void) {static int count = 0;count++;return count;}int fibonacci(void) {static int prev = 0;static int curr = 1;int next = prev + curr;prev = curr;curr = next;return prev;}void init_once(void) {static int initialized = 0;if (!initialized) {printf("Performing one-time initialization...\n");initialized = 1;}}int main(void) {printf("Call 1: %d\n", call_counter());printf("Call 2: %d\n", call_counter());printf("Call 3: %d\n", call_counter());printf("\nFibonacci: ");for (int i = 0; i < 8; i++) {printf("%d ", fibonacci());}printf("\n");printf("\n");init_once();init_once();init_once();return 0;}
call_counter increments a persistent counter. fibonacci maintains state between calls. init_once runs its body only on the first invocation. In all three cases, the static variable is invisible outside the function. No other function can read or modify count, prev, curr, or initialized. The state is encapsulated.
Static local variables are shared across all threads. If two threads call call_counter simultaneously, the count++ is a data race. The fix is a mutex, or making the function thread-local with __thread (GCC) or _Thread_local (C11). Static locals are safe in single-threaded code. In multithreaded code, they need the same protection as globals.
Static locals are function-private persistent state. They are cleaner than globals because they hide the state from the rest of the program. They are more powerful than locals because they survive across calls. Use them for counters, caches, and one-time initialization. Protect them with mutexes in threaded code. Next: a Python bonus lesson on enumerate, and then the course capstone.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.