Wednesday, 23 November 2016

Static Variable

Static Variable

A static variable initialize by 0 instead of garbage at the time of declaration. Static variable retain its value in memory till the program is running.

On the other hand auto variable lost its data when function scope pass out . But static variable retain its value whenever  scope get over.

You can trace that how many times a function is being called.

void test()
{
    static int k; /* k will retain its value when function scope goes down */
    printf("\nThis function being called %d times ",++k);
}

void main()
{
    int i;
    clrscr();
    for(i=1;i<=10;i++)
    {
         static int j;/* j will initialize only one  */
         printf("\t%d",j);
         j++;
    }
    test();
    test();
    getch();
}

As you can see in example test function has varaible k which retain its value when scope of function goes down. So every time when test function being called k will increment by 1 before printing and you count how many time test function called.

Another working form of static varaible you seen in for loop

for(i=1;i<=10;i++)
    {
         static int j;/* j will initialize only one  */
         printf("\t%d",j);
         j++;
    }

J will be initialize by zero and only one time, whereas static int j is running 10 times.