What is a static variable C?

A static variable is a special variable that is stored in the data segment unlike the default automatic variable that is stored in stack. A static variable can be initialized by using keyword static before variable name.


static int a = 5;

A static variable behaves in a different manner depending upon whether it is a global variable or a

local variable.A static global variable is same as an ordinary global variable except that it cannot be accessed by other files in the same program / project even with the use of keyword extern. A static local variable is different from local variable. It is initialized only once no matter how many times that function in which it resides is called. It may be used as a count variable.



//program in file f1.c

void count(void) {

static int count1 = 0;

int count2 = 0;



Value of count1 is %d, Value of count2 is %d", count1, count2);


Main function/

int main(){




return 0;



Value of count1 is 1, Value of count2 is 1

Value of count1 is 2, Value of count2 is 1

Value of count1 is 3, Value of count2 is 1