#include<stdio.h>
void print();
int main(){
print();
print();
return 0;
}
void print(){
static int x;
x=10;
x+=5;
printf("%d\t",x);
}
Output 15 15
#include<stdio.h>
void print();
int main(){
print();
print();
return 0;
}
void print(){
static int x;
x=10;
x+=5;
printf("%d\t",x);
}
Output 15 15
You have code that says:
x = 10;
x = 15;
and that then prints x.
Then you call that function two times.
Why again do you think that the second print should result in a different outcome; compared to the first one?!
You see, you start by assigning: 10. Plus 5. Why should that ever result in 20?
Hint - try changing your code to:
static int x = 10;
x += 5;
Long story short: re-assigning is not the same thing as re-initializing!
Here static
variable declared(initialized) as x
, then value assigned every time 10
not initialize.
So, output of your program 15
and 15
displayed.
initialization and assignment both are different. please read this stack overflow question.
I hope this will help you and make your doubt clear.
I think you are getting confused with Reassigning and Re-intializing of static variable. You must have learnt somewhere that static variable dosn't re-initialize itself whenever the function gets called. Hence you are expecting answer 15 & 20.
But the thing is that you are re-assigning the value of x with 10 each and every time. If you modify your code like following then you can achieve what you've expected.
static int x=10;
x+=5;
Here, x gets initialized with 10 first time only. After that, for each and every function call, it will get incremented by 5 only.
Hope this will help and make your doubt clear.