In the C language, the storage class of a variable determines where the data is stored, how long it is accessible, and which area of code can refer to it. Historically, the keywords auto (default for local variables), static (retains value between calls, often used to store state), and extern (declares a variable defined elsewhere) have been introduced for controlling the visibility and lifetime of variables.
Issue — misunderstanding where and how long a variable lives may lead to access errors, memory leaks, and hard-to-read code. For example, mistakenly expecting a local static variable to be recreated on each function call, or conversely, that an auto variable will retain its value between calls.
Solution — always consciously choose a storage specifier and understand its implications:
Example usage:
// main.c int global_var = 42; // has static storage class by default, external linkage void func() { static int counter = 0; // lives between calls auto int temp = 5; // local, auto does not need to be specified counter++; printf("call #%d\n", counter); } extern int global_var;
Key features:
Why even write auto, if variables are auto by default?
Answer: In modern versions of C, the keyword auto is rarely used explicitly — for local variables it is the default specifier. In general, its explicit writing offers no advantages.
Can static be used inside a function to declare a global variable?
Answer: No, static inside a function makes the variable local but state-preserving between calls. It is not visible outside the function.
Code example:
void foo() { static int call_count = 0; // Not global, but lives between calls call_count++; }
What happens if a variable is declared as extern inside a function but not defined anywhere?
Answer: This will lead to a linker error because a reference to a global variable that does not exist is declared.
In a large project, module variables were declared as extern in all source files but forgot to provide definitions. As a result — mysterious linking errors, unclear for novice developers.
Pros:
Cons:
Strictly defined scope: each static variable only in the necessary module, global extern declared in headers and defined in a single location.
Pros:
Cons: