J
jois.de.vivre
What happens when you return a reference to a local variable?
for example:
#include <iostream>
#include <cstdlib>
using namespace std;
int& testf()
{
int x = 1;
return x;
}
int main(int argc, char *argv[])
{
int &y = testf();
cout << y << endl;
return 0;
}
//--------end sample code
This results in outputting "1", but I don't understand whether that
makes sense intuitively. Wouldn't the local variable 'x' in testf() be
deallocated after the function returns? What, then would 'y' be
referencing? How come the compiler even allows this?
for example:
#include <iostream>
#include <cstdlib>
using namespace std;
int& testf()
{
int x = 1;
return x;
}
int main(int argc, char *argv[])
{
int &y = testf();
cout << y << endl;
return 0;
}
//--------end sample code
This results in outputting "1", but I don't understand whether that
makes sense intuitively. Wouldn't the local variable 'x' in testf() be
deallocated after the function returns? What, then would 'y' be
referencing? How come the compiler even allows this?