edited by
1,209 views

3 Answers

Best answer
8 votes
8 votes
//Debashish Deka: tester.c // GO
#include <stdio.h>
void p1(void) { .  //static var declared here are local only
     static int x = 10; // execute only once
     x += 5; 
     printf("%d\n",x);
}
void p2(void) {  //static var declared here are loocal only
     static int x; // execute only once
     x = 10; // execute every time
     x += 5; // execute every time
     printf("%d\n",x);
}



int main() {
     p1();
     p1();
     p2();
     p2();
     return 0;
}

O/P : 


Ok !

That was a bit simplification in the comments. What was happening under the hood is as follows.

  • in p1() The static x variable is allocated at link time and initialized at program load time. So there is no runtime code to allocate it nor to initialize it. The first code to access it is the +=5 statement. The variable x does not live in the stack.

If we use gdb to see what is going on .. 

  • 1. In the first call to p1() gdb does not stop at Line $4$, simply because, no runtime code for static declaration or initialization.

  • 2. Even before reaching declaration line static variable comes into existence, because of program executable load time initialization of variable x.

source

http://stackoverflow.com/questions/3270427/when-is-memory-allotted-to-static-variables-in-c

http://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-c

edited by
5 votes
5 votes
At first instance it seems to be 15 20 15 20 but actually I executed the code and got: 15 20 15 15
What I think is: the change happens at the initialization of x variable in the print2() func

In print1() initialization of value 10 is done at the time of declaration. because of static only one memory created at static storage and that value is updated which 15 then 20

now in print2() initialization is done after declaration. when memory is created one time its OK. first time value is 15 but next time when it is called and reach to x = 10 it updates the value of x to 10 first and then add 5 to it. which is again 15

hence the output: 15 20 15 15

Note: it's purely my analysis if anyone found it incomplete then please complete it!
–2 votes
–2 votes
answer is coming as 15 15 15 15

 

it seems like in this case scope of a static variable if declare inside a function is same as that of a local variable to that function each time function is called it is created and as function complete disposed off

Related questions

2 votes
2 votes
1 answer
1
0 votes
0 votes
1 answer
2
Markzuck asked Jan 10, 2019
521 views
Please explained detialed execution of this code, I am not getting how int stored in char, like we can interchange using ASCII but still cant store right?
1 votes
1 votes
0 answers
4