Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References in c++ with function

Tags:

c++

c++11

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

like image 692
Raghib Ahsan Avatar asked Oct 16 '15 02:10

Raghib Ahsan


3 Answers

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.

like image 110
songyuanyao Avatar answered Oct 11 '22 03:10

songyuanyao


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.

like image 20
franji1 Avatar answered Oct 11 '22 04:10

franji1


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.

like image 39
John Perry Avatar answered Oct 11 '22 03:10

John Perry