static variables have a lifespan and are stored in statically distributed memory. This means that the storage of local static variables inside a function is not allocated or freed up in the call stack.
As soon as x initialized at compile time, the value of x stored in memory between calls to the fun function.
Since C ++ statements are executed sequentially, printf will be executed after calling two function calls on the given lines
int *ptr=&fun(); int *ptr1=&fun();
therefore, the value of x will be 12 before executing the printf statements.
Keep in mind that
int *ptr=&fun(); int *ptr1=&fun();
not equivalent
int& (*ptr)() = &fun; int& (*ptr1)() = &fun;
In the second fragment, ptr and ptr1 both have the address of the fun function. In this case, you need to call the function directly or using these pointers as
int a = ptr(); int b = ptr1();
after this call value a and b will be 12 .
source share