Index
In C, storage classes define the scope (visibility) and lifetime of variables. Two important storage classes are static and extern. Here’s an explanation of each, along with examples:
1. static
The static storage class is used to declare variables that maintain their value between function calls. When a variable is declared as static, its lifetime extends to the duration of the program, but its scope is limited to the block in which it is declared. This means that the variable retains its value even after the function has finished executing.
Example of static
#include <stdio.h>
void increment() {
static int count = 0; // Static variable
count++; // Incrementing the static variable
printf("Count: %d\n", count);
}
int main() {
increment(); // Output: Count: 1
increment(); // Output: Count: 2
increment(); // Output: Count: 3
return 0;
}
Explanation:
- In this example, the
countvariable is declared asstaticwithin theincrementfunction. - Each time
incrementis called,countretains its value from the previous call, so it increments correctly. - If
countwere a regular local variable, it would be reinitialized to0every time the function is called.
2. extern
The extern storage class is used to declare a variable that is defined in another file or scope. It allows access to global variables from other files. When a variable is declared as extern, it does not allocate storage; it merely informs the compiler that the variable is defined elsewhere.
Example of extern
File 1: file1.c
#include <stdio.h>
int globalVar = 10; // Global variable
void display() {
printf("Global Variable: %d\n", globalVar);
}
File 2: file2.c
#include <stdio.h>
extern int globalVar; // Declaration of the external variable
void modify() {
globalVar += 5; // Modifying the external variable
}
int main() {
display(); // Output: Global Variable: 10
modify();
display(); // Output: Global Variable: 15
return 0;
}
Explanation:
- In
file1.c,globalVaris defined as a global variable. - In
file2.c,extern int globalVar;declares thatglobalVaris defined elsewhere (in this case, infile1.c). - The
modifyfunction modifies the value ofglobalVar. - When
displayis called inmain, it shows the updated value after callingmodify.
Summary
static:- Scope: Limited to the block in which it is declared.
- Lifetime: The variable retains its value between function calls and lasts until the program ends.
extern:- Scope: Accessible across multiple files.
- Lifetime: The variable is defined elsewhere, allowing other files to use it without redefining it.

