Reference Function Parameter Problem

I need to return several values from a function and I looked at our notes and noticed a reference parameter section. I'm not sure how to use this in my situation. Here's my code:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
int input;
int code();
void digits(int& x);
input=code();
cout<<d1; //This is where I want to use the values from
// void digits(int& x)
}
int code()
{
int codeInput;
cin>>codeInput;
return codeInput;
}
void digits(int& x)
{
int d1,d2,d3,d4,d5;
d1=x/10000;
d2=(x%10000)/1000;
d3=(x%1000)/100;
d4=(x%100)/10;
d5=x%10;
return;
}


//Do I need the "&" symbol to return more than one value?
I don't think you quite understand the idea of reference parameters. It's not quite "returning multiple values". When you pass a parameter normally, with no qualifying operators, the parameter is copied into the scope of the function. So in this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
void six(int);
int main()
{
    int seven = 7;
    six(seven);
    cout << seven;
    return 0;
}
void six (int five)
{
    five = 6;
    cout << five;
}

You get the output 67, not 66. It's because the parameter for six() is a copy of the version in main. They aren't connected to one another; modifying one does nothing to change the original.
Reference parameters work differently. They pass a handle to the parameter in question.
1
2
3
4
5
6
7
8
9
10
11
12
13
void six(int&);
int main()
{
    int seven = 7;
    six(seven);
    cout << seven;
    return 0;
}
void six (int& five)
{
    five = 6;
    cout << five;
}

This code will print 66. When you pass the reference, it's not a new variable or a copy, but the original thing under another name. Modifying the reference parameter doesn't modify a copy, but it actually changes the original one.
What reference parameters do is not "returning multiple values" - that is never possible. You can never return multiple things simultaneously. What you can do is pass the things you want changed as references in the function. Then you change them in function scope. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void changevalueref(int&, int);
int changevalue(int);
int main()
{
    int num = 2;
    num = changevalue(3);
    cout << num;
    changevalueref(num,2);
    cout << num;
}
int changevalue(int target)
{
    return target;
}
void changevalueref(int& original, int target)
{
    original = target;
}

In both cases the value of num is changed. But in one case, the value is changed by a return; in the second, it is changed in-function as a reference.
So no, you don't need the & operator to return more than one value, because you can't return more than one value. But the & symbol will qualify a parameter as a reference, which will enable you to modify the original value.
Topic archived. No new replies allowed.