I want to understand this snipped:
#include <iostream>
int& GetInt();
void Print(int& valueToPrint);
int main()
{
int& myValue = GetInt();
Print(myValue);
}
int& GetInt()
{
int x = 9;
return x;
}
void Print(int& valueToPrint)
{
std::cout << valueToPrint;
}
I was expecting this to print out 9, instead I get some high integer value of 32759. In my understanding, the function GetInt returns a reference to the variable myValue. I then pass this reference as a reference to the function Print.
My guessing is that this isn't working because x is defined inside the scope of GetInt and removed from stack memory after exiting this function. But why does my reference then get a strange random big integer number?