Understanding the Static Storage Class in C
Storage Class in C
Static variable is a variable whose value exists between function calls. It means, the static variable value will be retained even after coming out of a function, so that value can be used another function. Static variable is created on memory and initialized with default values like 0 or spaces.
Program: The initial default values for auto and static
#include<stdio.h>
void main()
{
auto float x;
static float y;
auto char str1[20];
static char str2[20];
printf("\nx= %f", x);
printf("\ny= %f", y);
printf("\nstr1= %s", str1);
printf("\nstr1= %s", str2);
}
In above program, we create auto and static variables but we do not initialize them. In case of auto variables, they are initialized with garbage values.
Program to understand the use of static variable
#include<stdio.h>
void test()
{
static int i=1;
auto int j=1;
printf("\n %d\t%d', i++, j++);
}
void main()
{
test();
test();
test();
}
Output:
1 1
2 1
3 1
In above program, we are taking two variables i and j in a function called ‘test()’. The variable i is taken as ‘static’ and j as ‘auto’. The incremented values of i and j are displayed in the function using a printf() statement. When the test() function is called from main(), we can see that the static variable ‘i’ is incremented every time and the auto variable j is not incremented.
Since i returned its value even after it came out of function, it is possible to increment upon that value. But j value is deleted immediately after coming out of the function. So, when the function is called again, it starts from 1 only. Thus, the static storage class makes the variable exist between function calls.