C Static Functions & Variables
In this page:
Static Local Variables
A static local variable is initialized only the first time its declaration is reached and then keeps its value between successive calls to the function, unlike an ordinary local variable which is recreated from scratch (and loses its previous value) every time the function runs.
Example: Static Local Variables
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("%d ", count);
}
int main() {
counter();
counter();
counter();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Static Global Variables
A static global variable is visible only within the source file where it's declared, meaning other .c files in the same project cannot access or accidentally modify it even if they declare a variable with the exact same name — the static keyword gives it file-level (internal) linkage instead of program-wide linkage.
Example: Static Global Variables
#include <stdio.h>
static int fileScoped = 42;
int main() {
printf("%d", fileScoped);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Static Functions
Declaring a function static restricts its visibility to the file it's defined in, which is useful for internal helper functions that other files have no legitimate reason to call directly, keeping your project's externally usable API smaller and more intentional.
Example: Static Functions
#include <stdio.h>
static int helper(int n) {
return n * 2;
}
int main() {
printf("%d", helper(5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Scope Isolation with Static
Because static functions and static global variables are invisible outside their own file, two different .c files in the same project can safely declare a static function or variable with an identical name without the linker ever reporting a naming conflict between them.
Example: Scope Isolation with Static
#include <stdio.h>
static int value = 10;
int main() {
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Memory Lifetime of Static Variables
Static variables live in the program's data segment rather than on the stack, meaning they are allocated exactly once when the program starts and continue occupying that memory for the program's entire runtime, regardless of how many times the function containing them is called.
Example: Memory Lifetime of Static Variables
#include <stdio.h>
void increment() {
static int total = 0;
total++;
printf("%d ", total);
}
int main() {
increment();
increment();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: