The storage duration of a variable defines the lifetime of that variable. In C, there are three storage durations:
For now, we will focus on the first one. The static
storage duration means that the variable will last for the entire execution time of the program. This means that a static variable will stay valid in the memory till the program is running.
It is important to note that lifetime and scope are two different concepts.
The Lifetime of a variable is the time duration in which a variable stays in the memory. The Scope of a variable determines the regions or blocks of code in which that variable can be accessed.
The difference between lifetime and scope is explained via code in the example below:
#include<stdio.h>void incrementAndPrint() {// declaring and initialising a static variablestatic int num = 2;// incrementing in the numbernum = num + 2;//printing the static variableprintf("Number: %d \n", num);}void main() {// calling the function twice to observe the behaviour of static variableincrementAndPrint();incrementAndPrint();}
In the code above, a static variable is created in the memory when the declaration statement (line 5) executes for the first time, i.e., during the first function call. When the function ends, the static variable is not deleted from the memory because its lifetime is valid until the program is running.
When the function is executed for the second time, the declaration statement is ignored and the variable’s value remains unchanged.
This behavior is evident by the output of the above program.
In the example above, if the main program is modified to:
void main() {
incrementAndPrint();
incrementAndPrint();
printf("Number: %d \n", num);
}
Then the num
variable would be undefined in the printf
function. The scope of the static num
variable is limited to the function in which it was declared.
This shows that, even if the static num
variable’s lifetime is of the entire program’s execution time, its scope is limited to the block in which it was declared.
Free Resources