Functions : Scope of a variable - Static Variable

Scope of a variable continued 

Static Variable
                       These are local variables in declaration and scope of accessing. The major difference with local variable is Static Variable preserves its value until entire program execution completes. It won't erases its value after every execution of a function/block. It is helpful keeping track of how many times the function is called/used.

Example :

Test( )
{
static int c=0;

c ++;
printf ( " \n Test function called %d times " ,c );
}
main( )
{
Test( );
Test( );
Test( );
}
In the above example, When main program execution starts a function Test() is called. Inside the Test() function first time a static variable c is declared with value zero. Then incremented by 1 and printed same on the output screen. As variable c is declared as static its value will not erased after completing the execution of Test() function.It will be preserved into memory. Second time the Test() function is called from main() the static variable c will not be re-declared, instead the previously declared variable and its value will be used. Even the at the third time calling of function Test() the same thing happens. Static variable is erased when main () program completes its execution.

Comments