The features of static storage class are as following:
Storage | Memory |
Keyword | static |
Default initial value | Zero |
Scope | Local to the block, in which the variable is defined |
Life | Value of the variable persists between different function calls. |
Let's compare static class with auto storage class for better understanding:
/*auto class*/
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
auto int i=1;
printf("\n%d",i);
i=i+1;
}
OUTPUT:-
1
1
1
1
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
auto int i=1;
printf("\n%d",i);
i=i+1;
}
OUTPUT:-
1
1
1
1
/*static class*/
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
static int i=1;
printf("\n%d",i);
i=i+1;
}
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
static int i=1;
printf("\n%d",i);
i=i+1;
}
1
2
3
4
The above both program consist of two functions main() and add(). The function add() gets called from main() four times. Each time it prints the value of i and then increments it. The only difference in these two programs is that one uses an auto storage class for variable i, whereas the other uses static storage class.
The difference between them is that static variable do not disappear when the function is no longer active. There value persist. If control comes back to the same function again , the static variables have the same values they had last time around.
Description of static program:
In static program, i is declare as static variable so it is initialized to 1 only once. It is never initialized again. During the first call to add(), i is incremented to 2. Because i is static, this value persists. The next time add() is called, i not re-initialized to 1, on the contrary, its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i=i+1; adds 1 to i to get a value of 3. When add() is called the third time , the current value of i (i.e. 3) gets printed and once again i is incremented by 1 and this process going so on till the add() called.
In summarised if the storage class is static, then the statement static int i = 1 is executed only once, irrespective of how many times the same function is called.
You might also like to read:
dear...thank you so much for this...i learnt from so many books and website..but i cleared my all doubt on this page..thanks a ton..GOD Bless You...
ReplyDeletethank you man...doubts busted..
ReplyDeleteis it possible to hide the functions and variables in c using static variable???
ReplyDelete