Could anyone please elaborate the behaviour of reference in this code and why is it printing 12 in 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;
}
the output of the code is
134519132 134519132 12 12
Please explain why 12 is getting printed on first call not 11 i understand when second call is made it should print 12
ptr
and ptr1
are pointing to the same variable static int x
. The second call changed the value of static int x
to 12
, then you print out the value by derefernce ptr
and ptr1
, the same result will be printed out.
The int reference returned by fun() is the same for both calls (ref to the static x), hence the address of that reference is the same for both calls. Hence the resulting dereference of that identical address is the current identical value.
Your error seems to be in thinking that printf()
prints *ptr
as soon as it comes available. It does not; printf()
is not called until both ptr
and ptr1
are computed. Since both ptr
and ptr1
point to the same memory location, which is a static variable, and that location is updated after both the first call to fun()
and the second, the address holds that value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With