-1
#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

Mukesh Ram
  • 6,248
  • 4
  • 19
  • 37

3 Answers3

4

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!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • as x is static it should first print 15 and then accordingly as x is static it should print 20 or not? – Dhruv Bhardwaj Aug 31 '16 at 04:49
  • 1
    See my updated answer. The point is: you are not "re-initializing". You are re-assigning. That is not the same thing. You know, you expect that `x = x + 5` gives x a new value; but then you expect that `x = 10` does not have an effect? – GhostCat Aug 31 '16 at 04:51
0

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.

Community
  • 1
  • 1
msc
  • 33,420
  • 29
  • 119
  • 214
0

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.

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37