Returning By Reference Question

Aug 10, 2015 at 5:12pm
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.
Aug 10, 2015 at 5:25pm
you shouldmight get garbage values
http://stackoverflow.com/a/6445794

You got lucky and that particular memory was not overwritten.
Try this, it has a higher chance to break something:
1
2
3
    int & sum = Sum(num1, num2);
    std::cout << std::endl;
    std::cout << sum << std::endl;
Last edited on Aug 10, 2015 at 5:25pm
Aug 10, 2015 at 6:05pm
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}
Last edited on Aug 10, 2015 at 6:05pm
Aug 10, 2015 at 6:11pm
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:
1
2
3
4
5
6
int& inc()
{ 
    static int foo = 0;
    ++foo;
    return foo;
}
Aug 10, 2015 at 6:32pm
Thanks for the help Miinipaa. I was really confused there.
Aug 10, 2015 at 11:13pm
Glad you had your problem solved :D I just wanted to mention... Don't use system("pause"). I don't wanna go into a rant, so you can look it up. Use
1
2
std::cin.ignore();
std::cin.get();
instead. It does the job nicely.
Topic archived. No new replies allowed.