Storage duration of static variables in C
The keyword static
provides different behaviors in different languages. The first time I learned about static
was with C, but I didn’t remember how it behaved. Now I learned that static
is used to allocate static memory when defining a variable in C. Once a variable is declared static
, the storage duration of the object will be the whole execution of the program. Consider this example:
#include<stdio.h>
#include<stdlib.h>
int increment() {
int num = 0;
num++;
return num;
}
int main(void) {
for (int i=0; i < 5; i++) {
int result = increment();
printf("Number: %d\n", result);
}
return 0;
}
The execution of this program will print the following lines:
Number: 1
Number: 1
Number: 1
Number: 1
Number: 1
The reason for this program to print the same numbers over and over is because we are redeclaring the num
variable within the increment()
function. Every time this function is called, we redeclare it with a constant 0, and then increment and return the number. That’s why each and every one of those lines are printing Number: 1
. This is because the declaration of int num
has something called a function scope. Once the execution is out of the function, the object is out of scope.
What if we allocate static storage for the object identified by num
? Consider the slightly changed example below:
#include<stdio.h>
#include<stdlib.h>
int increment() {
static int num = 0;
num++;
return num;
}
int main(void) {
for (int i=0; i < 5; i++) {
int result = increment();
printf("Number: %d\n", result);
}
return 0;
}
The execution of this program will print the following lines:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
It looks like the program execution achieved what it was supposed to do: Increment. The reason it correctly incremented this time is because the object identified by num
had a static storage. The duration of this storage was the execution of the whole program. Although we are still redeclaring the variable every time we call increment()
, the storage of the object is not changed. The program picks up the value stored in the exact same location, increments and returns it.
This is how a single keyword change on the variable declaration causes two different behaviors. And that’s one of the reasons why I couldn’t pick up the C language when I was first learning it: I didn’t pay attention to memory allocations before.