Any value assigned to an automatic variable within a function is lost once the control returns from the called function to the calling function. However, there may be a situation where the value of the local variable needs to be preserved even after the execution of the function gets over. This need can be fulfilled by declaring the variable as static. A static variable is commonly used when it is necessary for a function to remember a value between its calls. To understand the concept of static variables, consider this example.
Example : A program to demonstrate the use of static variables within a function
#include<iostream> using namespace std; void count () { static int c=0; c++; cout<<”Function is called "<<c<<" times\n"; } ; int main () { for (int i=1;i<=5;i++) count() ; return 0; }
The output of the program is
Function is called 1 times
Function is called 2 times
Function is called 3 times
Function is called 4 times
Function is called 5 times
In this example, c is a static variable declared in function count (). This variable is incremented by one each time the function is called. Note that the static variable is initialized to 0 only once when the function is called for the first time. In subsequent calls, the function retains its incremented value from the last call (see output).