Static Storage Class

The feature of a variable whose storage class is static are:
-The variable is stored in memory
-Its default initial value is 0
-The scope of the variable is local to the block in which it is defined
-The value of the static variable persists until the end of the program.

Though the scope of static variable is local only to the block in which it is declared, the variable does not disappear but remains alive throughout

the program. The scope of auto variable as we have seen is also local and the value of these variables are no longer available once control goes out of the

block in which they are declared.Static variable are therefore useful when we wish to retain the value of the variables during function calls. A static

variable is initialised only once when the program is compiled. It is never initialised again. The following example illustrates the use of static variables:

Example:
main()
{
fn1();
fn1();
fn1();
}
fn1()
{
static int i=10;
printf("\ni=%d",i);
i=i+1;
}

The output of the program will be:
i=10
i=11
i=12

No comments:

Post a Comment