My understanding of returning by reference is that when you return a local variable by reference from a function, you should get garbage values, but the following code says otherwise.
int & Sum(int num1, int num2);
int main()
{
int num1 = 1;
int num2 = 1;
int & sum = Sum(num1, num2);
std::cout << sum << std::endl;
system("Pause");
return 0;
}
int & Sum(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
The sample code above still prints out 2 despite the fact that the variable sum is a local variable that is defined in the function Sum. I thought I should have gotten a garbage value from this like (0x25695 or -154826), or something of that nature.
So is the bottom the only safe way of returning by reference or by pointer? Where the parameter is passed as a reference and is returned as a reference.
int & Change(int & num);
int main()
{
int num = 5;
int & value = Change(num);
std::cout << value << std::endl;
system("Pause");
return 0;
}
int & Change(int & num)
{
num = 6;
return num;
}
Yes. This is safe. You can safely return reference to what you got as reference parameter.
It is often used to chain calls. In fact you was usng it in your first program — this is how stream operators work:
1 2 3 4 5 6 7 8
std::ostream& operator<<(std::ostream& out, <second parameter>)
{
//Do work
//Return left hand side parameter
//to be used as first argument in next operator call
return out;
}
Also you can safely return references to static variables: