ProgrammingC Developer

How do static local variables work in functions in C? What is their difference from regular local variables? Provide examples of use and potential errors.

Pass interviews with Hintsage AI assistant

Answer

A static local variable is defined using the static keyword inside a function. Unlike regular local variables, it retains its value between function calls and is initialized only once. Such a variable exists for the lifetime of the program but is only visible within its function.

Regular local variable:

void func() { int count = 0; // initialized every time count++; printf("%d\n", count); }

Each time the output will be — 1.

Static local variable:

void func() { static int count = 0; // initialized only once count++; printf("%d\n", count); }

For consecutive calls, we get the output: 1, 2, 3, ...

Usage: convenient for counting the number of function calls, caching simple values.

Trick question

"Will a static local variable be destroyed after exiting the function and what will happen to its value during the next function call?"

Often answered that it gets destroyed, but that's not true.

Correct answer: A static local variable exists for the entire lifetime of the program. It retains its value between function calls and is initialized only once (at the first entry into the function, or before main).

Examples of real mistakes due to ignorance of the nuances of the topic


Story 1

In a project, the entrance time metrics to a module were measured through a function that was supposed to count each access. Confused int counter = 0; with static int counter = 0; — the function always returned 1, making the statistics useless.


Story 2

In a non-thread-safe service, a static variable was used in a function that was called from different threads. This led to race conditions and random incorrect results. It was not taken into account that shared memory is not protected.


Story 3

A pointer to dynamically allocated memory was stored in a static variable for caching. Upon restarting the function, the old memory was not freed: this caused a memory leak on each call.