Skip to content
Home » How does static variable work in C

How does static variable work in C

Static variables have the property of retaining their value even after they have been removed from their scope! As a result, static variables retain their previous value in their previous scope and are not re-initialized in the new scope. Below examples illustrate about static variable.

#include<stdio.h>
void test()
{
    int a=10;
    static int b=20;//initializing static variable
    a++;
    b++;//b is not re-initialized
    printf(" the values of a and b are %d ,%d \n",a,b);
}
int main()
{
    int i=0;
    while(i<10)
    {
        test();
        i++;
    }
    return 0;
}

the values of a and b are 11 ,21
the values of a and b are 11 ,22
the values of a and b are 11 ,23
the values of a and b are 11 ,24
the values of a and b are 11 ,25
the values of a and b are 11 ,26
the values of a and b are 11 ,27
the values of a and b are 11 ,28
the values of a and b are 11 ,29
the values of a and b are 11 ,30

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Also read:

Static Int as counter