Answer: Static variable in C programming is the variable which value persists between different function calls throughout the life cycle of the program.
For example, in the below function staticVarCount (), the s is a static variable, and when we make a call again and again, its value will be increased e.g.1,2,3…and so on. Value of s will persist, even though its scope is within the function itself.
Static variable code example in C
staticVarCount(){
static int s = 0;
++s;
printf("Static Variable:%d\n",s);
}
Non static variable
Below is the same function implementation with non static variable s. when we make multiple calls, its value will be always 1 as variable s will die as soon as control goes out of the function.
nonStaticVarCount(){
int i = 0;
++i;
printf("Non Static Varable:%d\n",i);
}
Complete code of Static Variable and Non Static variable in C
//Function with static variable
staticVarCount(){
static int s = 0;
++s;
printf("Static Variable:%d\n",s);
}
//same function with non static variable
nonStaticVarCount(){
int s = 0;
++s;
printf("Non Static Varable:%d\n",s);
}
int main(){
staticVarCount();
staticVarCount();
nonStaticVarCount();
nonStaticVarCount();
return 0;
}
Output:
Static Variable:1
Static Variable:2
Non Static Varable:1
Non Static Varable:1
NOTES:
- Static variables in c and c++ automatically get initialize by zero, if we don’t initialize it by zero or some number.
- There can be a Global and local Static variable in c. Local static variable will be always taken on priority within the scope. Do read example below.
Global and Local Static variable C Code Example
#include
static int s = 5;//Global Static varialbe
int main(){
static int s = 10;//Local Static varialbe with same name
printf("Value of s:%d\n",s);
return 0;
}
Output:
Value of s:10