0

If i remove this 'static' then nothing will print what is the reason behind this?

#include<stdio.h>
int *fun();
int main()
{
 int *p;
 p=fun();
 printf("Address=%u\n",p);
 printf("Value at that address=%d\n",*p);
 return 0;
}
int *fun()
{
 static int i=1;
 return (&i);
}

1 Answers1

3

Don't reason about undefined behavior. Without static it is a local variable's address that you return from the function. Accessing a local variable when its life time is over results in undefined behavior. It might give you the correct result and the very next time it may blow up. Undefined behavior it is.

With static the variable has lifetime beyond the scope of the function. Then you can return its address and access it outside the function because the life time is now not dependent on the called function.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
user2736738
  • 30,591
  • 5
  • 42
  • 56
  • so is "static" making variable global?? – Shubham kesarwani Dec 12 '17 at 17:25
  • @Shubhamkesarwani: It is making is static. Scope and lifetime are different things. With or without `static` it is a local variable. Without `static` it is an automatic local variable, with `static` it is a static local variable. – AlexP Dec 12 '17 at 17:27
  • @Shubhamkesarwani Not exaclty in this case. A `global` variable can be viewed/acessed by the whole code by its name. The fact that `i` is `static` here, means that the value of `i` will be stored in an address and stay there even after the function call (Regardless of the scope of `i`) – kyriakosSt Dec 12 '17 at 17:30
  • @Shubhamkesarwani.: *Objects with automatic storage duration live for the lifetime of the block in which they execute.* - which is the case when `static` keyword is not there. With static, *Objects with static storage duration live for the lifetime of the program.* – user2736738 Dec 12 '17 at 17:32