Links in C ++ with a function

Can anyone think of the link behavior in this code and why it prints 12 in the first line instead of 11.

Below is the code

http://ideone.com/l9qaBp

#include <cstdio> using namespace std; int &fun() { static int x = 10; x++; return x; } int main() { int *ptr=&fun(); int *ptr1=&fun(); printf("%p %p \t %d %d",(void*)ptr,(void*)ptr1,*ptr,*ptr1); return 0; } 

code output

134519132 134519132 12 12

Please explain why 12 is printed on the first call, not 11 . I understand when the second call is made, it should print 12

+6
source share
4 answers

It seems your mistake is that printf() prints *ptr as soon as it appears. Is not; printf() not called until both ptr and ptr1 . Since both ptr and ptr1 point to the same memory location, which is a static variable, and this location is updated after the first call to fun() and the second, the address saves this value.

+2
source

ptr and ptr1 point to the same static int x variable. The second call changed the value of static int x to 12 , then you print the value using derefernce ptr and ptr1 , the same result will be printed.

+4
source

The int reference returned by fun () is the same for both calls (ref for static x), so the address of this link is the same for both calls. Therefore, the result of dereferencing this identical address is the current identical value.

+3
source

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 .

0
source

All Articles