The static keyword in C is used to control the visibility and lifetime of variables and functions. It can be applied to both variables and functions.
1. Static Global Variable
2. Static Function
3. Static Local Variable
4. Static Member Variables (in C++)
5. Static Method (in C++)
A static global variable is declared at the top of the program with the static keyword.
It is accessible only within the file where it is declared.
#include <stdio.h>
static int count = 0; // Static global variable
void increment() {
count++;
printf("Count: %d\n", count);
}
int main() {
increment();
increment();
return 0;
}
Count: 1
Count: 2
A static function is a function declared with the static keyword.
It is only accessible within the file it is declared in.
#include <stdio.h>
static void displayMessage() { // Static function
printf("Hello, static function!\n");
}
int main() {
displayMessage();
return 0;
}
Hello, static function!
A static local variable is declared inside a function with the static keyword.
Its value persists between function calls.
#include <stdio.h>
void counter() {
static int count = 0; // Static local variable
count++;
printf("Count: %d\n", count);
}
int main() {
counter();
counter();
counter();
return 0;
}
Count: 1
Count: 2
Count: 3
The memory for a static variable is allocated once and remains allocated throughout the program's lifetime.
If not explicitly initialized, static variables are automatically initialized to zero.
The scope of a static local variable is limited to the function in which it is declared.
The scope of a static global variable or function is limited to the file in which it is declared.
Static local variables retain their value between function calls.
Declared outside any function.
Accessible throughout the program.
Can be accessed by other source files if declared with extern.
Declared with the static keyword.
Static global variables are only accessible within the file they are declared in.
Static local variables persist their value between function calls but are only accessible within the function they are declared in.