Static variables in C
By Flavio Copes
Learn how static variables work in C: declared with the static keyword inside a function, they default to 0 and keep their value across function calls.
A static variable in C is a variable declared inside a function with the static keyword. It’s initialized to 0 if no initial value is specified, and it retains its value across function calls.
I said “inside a function”, because global variables are static by default, so there’s no need to add the keyword.
How does it behave?
Consider this function:
int incrementAge() {
int age = 0;
age++;
return age;
}
If we call incrementAge() once, we’ll get 1 as the return value. If we call it more than once, we’ll always get 1 back, because age is a local variable and it’s re-initialized to 0 on every single function call.
If we change the function to:
int incrementAge() {
static int age = 0;
age++;
return age;
}
Now every time we call this function, we’ll get an incremented value:
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
will give us
1
2
3
We can also omit initializing age to 0 in static int age = 0;, and just write static int age; because static variables are automatically set to 0 when created.
Where does a static variable live?
A normal local variable lives on the stack. It’s created when the function is called, and destroyed when the function returns.
A static variable is stored in the data segment of the program instead. It exists for the entire life of the program. Only its visibility is limited: no other function can access age by name, but the value survives between calls.
This also means the state is shared. Every caller of incrementAge() increments the same counter. That’s the whole point of the feature, but keep it in mind: a function with static state is not safe to call from multiple threads without synchronization.
Static arrays
We can also have static arrays. In this case, each single item in the array is initialized to 0:
int incrementAge() {
static int ages[3];
ages[0]++;
return ages[0];
}
One pitfall
In C, the initializer of a static variable must be a constant expression. You can’t initialize it with the result of a function call:
static int age = getStartingAge();
/* error: initializer element is not constant */
If you need a computed starting value, initialize the variable to a sentinel value like 0, and compute the real value on the first call.