static {data type} {variable name}
Static local variables
When a variable in a function is static, the variable preserves its value between function calls.
#include<stdio.h>
int fun1()
{
int count=0;
count++;
return count;
}
int fun2()
{
static int count=0;
count++;
return count;
}
int main()
{
printf("fun1 1st call returns : %d\n",fun1());
printf("fun1 2nd call returns : %d\n\n",fun1());
printf("fun2 1st call returns : %d\n",fun2());
printf("fun2 2nd call returns : %d\n",fun2());
return 0;
}
In Example 1.c, we have two functions: fun1() and fun2(). In fun1(), we declare one variable (count) and initialize it to 0. Then, we increment the count variable and return the resulting value. Using main(), we call fun1() twice, and each time, a value of 1 is returned because the count variable is cleared when the call to fun1() is completed. In fun2() we declared the count variable as a static variable. Therefore, its value is preserved. Using main(), we call fun2() twice: the first time, a value of 1 is returned, and the second time, a value of 2 is returned.
Static global variables
A static global variable behaves in the same way as other global variables, but it cannot be accessed from another C program.
Static functions
In C, functions are global by default. However, if we declare a static function, then the function is local and cannot be accessed from another C program.
Initialization of static variables
If a static variable is not explicitly initialized, then it is initialized as 0.
#include<stdio.h>
int main()
{
static int i;
printf("Value of i : %d\n",i);
return 0;
}
In Example2.c, we declared a static variable i that is not initialized. However, because the variable is static, it is automatically initialized to 0.
It is important to note that a static variable must be initialized by a constant literal; we cannot use a function’s return value to initialize a static variable.
#include<stdio.h>
int fun1()
{
return 5;
}
int main()
{
static int i = fun1();
printf("Value of i : %d\n",i);
return 0;
}
In Example3.c, we try to initialize a static variable by using the return value of fun1(). However, as you can see, an error is returned when the code is compiled.
Summary
The lifetime of a static variable and the lifetime of the program are equal.
If a static variable is not initialized, then it will take on a default value of 0.
Neither a global static variable nor a static function is accessible from a program other than the one in which it was defined.