|
static Storage Type
As opposed to auto type data, C++ also
offers static type data, which, as its
name suggests, retains its value even
after the function to which it belongs
has been executed. The following
example illustrates the difference
between auto static type data:
//Program 8.2
//Program to differentiate between
auto and static type data
#include<iostream.h>
void dummy(void);
void main(void)
{
int iVar;
for(iVar=0; iVar<3; iVar++)
{
dummy();
}
void dummy(void)
{
int iCtr = 1;
cout<<"Function executed"<< iCtr <<
"time"<< endl;
iCtr++;
}
The Output of Program 8.2 would be:
Funtion executed 1 time
Funtion executed 1 time
Funtion executed 1 time
//Program 8.3
//Program to differentiate between
auto and static type data
#include<iostream.h>
void dummy(void);
void main(void)
{
int iVar;
for(iVar=0; iVar<3; iVar++)
{
dummy();
}
}
void dummy(void)
{
static int iCtr=1;
cout<<"Function executed" << iCtr << "time(s)"<<endl;
iCtr++;
}
In the programs shown, the function
dummy() is used to print the number of
times the function has been called.
Execution stops when the value of the
variable iCtr in the function main()
reaches three.
The output of Program 8.3 would be:
Function executed 1 time(s)
Function executed 2 time(s)
Function executed 3 time(s)
This is because, in Program 8.2 the
variable iCtr is declared as auto type
data. Therefore, every time the
function dummy() is called, the
variable gets created and initilized
to 1. But the static declaration in
Program 8.3 ensures that the variable
is declared is declared and
initialized only once, that is, when
the funtion is invoked the very first
time.
Arrays declared as static can be
initialized within a function at the
time of declaration. |