1
#include <iostream>
using namespace std;

int f() 
{
    int x=1;
    return x;
}

int main()
{
    const int& s = f();
    cout << s << endl;
}

#include <iostream>
using namespace std;

int x=1;

int &f() 
{
    return x;
}

int main()
{
    const int& s = f();
    cout << s << endl;
}

Both of these programs are correct. But when I use

int &f() 
{
    int x=1;
    return x;
}

instead of

int f() 
{
    int x=1;
    return x;
}

I get an error:

main.cpp: In function 'int& f()':

main.cpp:6:13: warning: reference to local variable 'x' returned [-Wreturn-local-addr]

     int x=1;

         ^

bash: line 7: 14826 Segmentation fault (core dumped) ./a.out

What's wrong?

  • the x in the f() function is local to the function and is "destroyed" when the function returns (its allocated on the call stack). So if you are trying to return a reference to that destroyed variable, you'll get that causing the error. – Moop Feb 08 '19 at 07:42
  • You might want to [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and read about life-time of variables. – Some programmer dude Feb 08 '19 at 07:43

1 Answers1

0
int &f() 
{
    int x=1;
    return x;
   // x reside on the function calling stack and it is temporary
   // when you return the reference to x, after the function has returned, 
   // x is not there anymore(local variable)
}

if you really want to return a reference to a variable declared inside a function, consider allocate it on the heap, or declare it as a static variable

    int &f() 
    {
        int* x= new int;
        *x = 1;
        return *x;
    }
    int main(){
        int& a = f();
        cout << a; // 1
        delete &a;
        // and MAKE SURE you delete it when you don't need it
    }
May
  • 101
  • 7