Output: 15 20 15 15
Few things you should note here
- Static variable retain their value even after they are out of scope
- Initialization of static variable is done only once
Most of you already are knowing this.
void print1(void){
static int x=10; // x is declared as well as initialized , this statement will be executed only once
x+=5;
printf("%d",x);
}
print1() 1 st call
void print1(void){
static int x=10; // x=10
x+=5; // x=15
printf("%d",x); // prints 15
}
print1 2nd call
void print1(void){
static int x=10; // not be executed
// x value is 15 as static variable value is retained
x+=5; // x=20
printf("%d",x); // prints 15
}
Now print2()
void print2(void){
static int x; // x is declared and initialized to 0, this will be executed only once
x=10; // this is assignemnt of value to x and will be executed each time print2() is called
x+=5;
printf("%d",x);
}
print2() first call
void print2(void){
static int x; // x=0
x=10; // x=10
x+=5; // x=15
printf("%d",x); // prints 15
}
print2() 2nd call
void print2(void){
static int x; // not be executed
x=10; // x=10
x+=5; // x=15
printf("%d",x); // prints 15
}