I read that : static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. from the link.
then why I am getting error that "i was not declare " in the code given below. I wrote program such that the static variable "i" initialized only first time when c is equal to 0 after that c increases. I just want to know how the static variable really works and that's why i am declare static variable only once. My question is if static variable only declare once in each function call then why my code is not running and if it is necessary to declare it in each calling then why it does not initialise in each function call.
#include<stdio.h>
int c=0;
int test()
{
if(c==0)
{
static int i=0;
}
c++;
i++;
if(i==5)
printf("%d\n",i);
else
test();
}
int main()
{
test();
return 0;
}
You define the variable inside the local scope of if
. It has no scope outside. static
only deals with the extent (aka lifetime).
Use curly braces and indention. Then you will see your mistake.