static Variables
Persistent locals.
The static Keyword
A static local variable keeps its value between calls to the function. Its lifetime is the whole program.
#include <stdio.h>
void f(void) {
static int count = 0;
count++;
printf("count = %d\n", count);
}
int main(void) {
f();
f();
f();
return 0;
}Initialized Once
A static variable is initialized only the first time the function runs. Later calls skip the initializer.
#include <stdio.h>
void f(void) {
static int x = 100;
printf("x = %d\n", x);
x += 10;
}
int main(void) {
f();
f();
return 0;
}All lessons in this course
- auto and Local Scope
- static Variables
- extern and Global
- register and const