What is the static variable ..

Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Syntax:
static data_type var_name = var_value; 
Following are some interesting facts about static variables in C.
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.
For example, we can use static int to count a number of times a function is called, but an auto variable can’t be used for this purpose.

2) By default static variable are initialized by 0;
Example:-
 

If we use static variable then varialble is initialized only one time as in the following program;-
#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf(“%d “, fun());
printf(“%d “, fun());
return 0;
}

The output of the above program is 1 2.
And if we use ordinary variable then output is

#include<stdio.h>
int fun()
{
int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

The output of above program is 1 1.




Leave a Reply

Your email address will not be published.