-
static variable result
Code:
#include<stdio.h>
void foo ()
{
static int i = 0;
printf("i = %d \n", i);
i = 1;
printf("i = %d \n", i);
i = 2;
printf("i = %d \n", i);
i = 3;
printf("i = %d \n", i);
}
int main ()
{
foo ();
printf("\n");
foo ();
return 0;
}
First Call
i = 0
i = 1
i = 2
i = 3
Second Call
i = 3
i = 1
i = 2
i = 3
because of static keyword i become equal to 3. exactly. When code run what happen in program ?
-
Just remember that a static local variable retains its value after control returns to the caller. That's why the apparently initial value of i was 3 on the second call to foo.
-
Does this confuse you less?
Code:
#include<stdio.h>
static int i = 0;
void foo ()
{
printf("i = %d \n", i);
i = 1;
printf("i = %d \n", i);
i = 2;
printf("i = %d \n", i);
i = 3;
printf("i = %d \n", i);
}
int main ()
{
foo ();
printf("\n");
foo ();
return 0;
}
The only difference here is that the variable called i now has a scope that extends to the whole file, and not just the foo() function.