94 Introduction to C++ Programming and Graphics
As an example, running the program:#include <iostream>
using namespace std;void counter();//--- main:int main()
{
for(int i=1;i<3;i++)
{
counter();
}
cout << endl;return 0;
}//--- function counter:void counter()
{
static int n=0;
n++;
cout << n << " ";
}prints on the screen:
12Every time the functioncounteris entered, the static variablenincreases by
one unit. A static variable can be used to count the number of times a function
is called from another function.
In another application, we use thestaticdeclaration to prevent a vari-
able from being reinitialized:
for (i=1;i<=5;i++)
{
static int count = 0;
count++;
}At the end of the loop, the value ofcountwill be 5, not 1.