Static Variables

In the case of single file programs static variables are defined within functions and individually have the same scope as automatic variables. But static variables retain their values throughout the execution of a program within their previous values.

Points to remember:

• The specifier precedes the declaration. Static and the value cannot be accessed outside of their defining function.
• The static variables may have the same name as that of external variables but the local variables take precedence in the function. Therefore external variables maintain their independence with locally defined auto and static variables.
• An initial value is expressed as the constant and not expression.
• Zeros are assigned to all variables whose declarations do not include explicit initial values. Hence they always have assigned values.
• Initialization is done only is the first execution.

Let us study this sample program to print the value of a static variable:

/* Program to illustrate the use of static variable*/
#include <stdio.h>
main()
{
int call_static();
int i,j;
i=j=0;
j = call_static();
printf(“%d\n”,j);
j = call_static ();
printf(“%d\n”,j);
j = call_static();
printf(“%d\n”,j);
}
int call_static()
{
static int i=1;
int j;
j = i;
i++;
return(j);
}

OUTPUT 
1
2
3

This is because i is a static variable and retains its previous value in the next execution of function call_static( ). To remind you j is having auto storage class. Both functions main and call_static have the same local variable i and j but their values never get mixed.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: