Keyword | static |
Storage | Data Memory |
Default Initial Value | Zero |
Scope | Local to the block in which the variable is defined. |
Life | Value of the variable persists between different function calls. |
int main( )
{
increment( ) ;
increment( ) ;
increment( ) ;
return 0;
}
int increment( )
{
static int i = 1 ;
printf ( "%d\n", i ) ;
i = i + 1 ;
return 0;
}
The output of the above programs would be:
1
2
3
static
variables are local to the block in which they are declared. The static
variable is initialized once and the value of a static
variable persists even after the control goes out of function. If the control comes back to the same function again the static
variables have the same values they had last time around. Therefore, making local variables static
allows them to maintain their values between function calls. The
static
modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
Related topics:
Overview of Storage Class in C | Auto Storage Class in C | Register Storage Class in C | Extern Storage Class in C | Summary of Storage Class in C
List of topics: C Programming
No comments:
Post a Comment