In C, the static
keyword has three primary uses, depending on the context in which it is applied:
1. Static Variables Inside a Function
When static
is used to declare a local variable inside a function, it changes the variable’s storage duration from automatic (default) to static. This means:
- The variable is initialized once (when the program starts) and retains its value between function calls.
- It is not reinitialized each time the function is called.
- Memory is allocated in the static memory area (not the stack).
Example:
void counter() {
static int count = 0; // Retains value between calls
count++;
printf("Count: %d\n", count);
}
int main() {
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
return 0;
}
2. Static Global Variables
When static
is applied to a global variable (declared outside any function), it limits the variable’s linkage to the current file. This means:
- The variable is not visible to other source files (prevents
extern
access). - It avoids naming conflicts in large projects.
Example:
// File: utils.c
static int internalVar = 42; // Only visible within utils.c
void printVar() {
printf("%d\n", internalVar); // Accessible here
}
// File: main.c
extern int internalVar; // ERROR: Linker cannot find this variable
3. Static Functions
When static
is used for a function, it restricts the function’s visibility to the current source file. This means:
- The function cannot be called from other files.
- It helps encapsulate helper functions and avoid naming collisions.
Example:
// File: math_utils.c
static int square(int x) { // Only visible in math_utils.c
return x * x;
}
int computeSquare(int x) {
return square(x); // Can call the static function
}
// File: main.c
int square(int x); // ERROR: Cannot access static function
Key Differences Between Contexts
Context | Behavior |
---|---|
Local Variable | Retains value between function calls; initialized once. |
Global Variable | File-scoped; not visible to other files. |
Function | File-scoped; cannot be called from other files. |
Additional Notes
- Default Initialization: Static variables (global or local) are initialized to
0
if no explicit value is provided. - Thread Safety: Static variables inside functions are not thread-safe (shared across threads).
- Memory Allocation: Static variables persist for the program’s lifetime and are stored in the data segment.
By using static
, you control variable persistence, encapsulation, and visibility, making code more modular and secure.