One of the most common question while attending interview is about the Static Variable, in this article I tried to summarize the behavior of static variable in C.
Static Variable can be understood in two different cases -
1) Static variable is Inside a Function or a Block
a. Life Time of variable is life of the program i.e. there exist even after your block is not in the execustion.
b. When the control reaches to same block or function the old value is retained
c. These variable are initialized as zero and are stored in the BSS of the process.
Example
void func() {
static int x; // x is initialized only once with 0 across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main() {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
$./a.out
0
1
2
2) Static Variable is Outside a function
a. When we have static variable outside of a function then one more angle is added is the variable carries a file scope.
b. If your process have multiple files then the variable can be used only in the file in which it is defined.