In the following code, two functions are demonstrated. f1() returns the reference of the initialized local variable in the function scope, f2() returns the value of the initialized local variable in the function scope.
f2() is expected to work well because locally initialized variable. Value is passed from the stack to the main.
f1() is not expected to work because the reference of the local variable is useless out of the function scope. However, the output seems to ok for both functions.
Here is the test code;
#include <iostream>
using namespace std;
// function declarations
int& f1();
int f2();
int main()
{
cout << "f1: " << f1() << endl; // should not work!
cout << "f2: " << f2() << endl; // should work
return 0;
}
int& f1() // returns reference
{
int i = 10; // local variable
return i; // returns reference
}
int f2() // returns value
{
int i = 5; // local variable
return i; // returns value
}
The output is as follows;
f1: 10
f2: 5
Why f1() is working fine even that f1() returns reference of the local variable?