Static Variables:
The static variable may be of an internal or external type, depending upon where it is declare. If declared outside the function of the body it will be static global. In case it is declared in the body or block, it will be static auto variable.
When a variable is declared as static, its garbage value is removed and initialized to NULL value. The contents stored in these variables remain constant throughout the program execution. A static variable is initialized only once; it is never reinitialized.
The value of the static variable persists at each call and the last change made in the value of the static variable remains throughout the program execution. Using this property of static variable we can count the number of times a function is called.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
for(;;)
print();
}
print()
{
int static m;
m++
printf(“\nm+%d”,m);
if(m==3)
exit(1);
}
OUTPUT:
m=1
m=2
m=3
Explanation:
In the above program, print() function is called. The variable ‘m’, of print() function is a static variable. It is increased and printed in each call. Its content persists at every call. In the first call its value is changed from 0 to 1, in the second call 1 to 2 and in the third call 2 to 3.