returning references

my question is involving returning a reference. from playing around, i have only been able to get it to function (no pun intended xD) when its returning the adress of an element in an array. is it not possible to return a reference to a variable or am i doing something wrong? here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using std::cout;
using std::endl;

int& changeNumber(int num);

int main()
{
	int number = 50;
	changeNumber(number) = 3;
	cout << number << endl;

	return 0;
}

int& changeNumber(int num)
{
	return num;
}


just for reference(HAHHA ANOTHER PUN) here is the working code when using an array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iomanip>
using std::setw;
using std::cout;
using std::endl;

int& changeNumber(int num[]);

int main()
{
	int number[3] = { 32, 35, 26 };
	changeNumber(number) = 50;
	
	for (int i = 0; i < 3; i++)
		cout << setw(6) << number[i];

	cout << endl;
	return 0;
}

int& changeNumber(int num[])
{
	int y = 0;
	for (int i = 0; i < 3; i++)
		if (num[y] < num[i])
			num[y] = num[i];
	
	return num[y];
}
Last edited on
In this case, you are returning a reference to a *copy* of num, which is dangerous because the copy is destroyed before you can change it.

You would have to pass the number in by reference or pointer if you want to be able to return a reference to it safely.
is this what you meant by use pointers?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using std::cout;
using std::endl;

int& changeNumber(int* num);

int main()
{
	int number = 50;
	int* pnumber = &number;
	changeNumber(pnumber) = 3;
	cout << number << endl;

	return 0;
}

int& changeNumber(int* num)
{
	return *num;
}
Yes.
in that case thank you good sir :)
Topic archived. No new replies allowed.