References Exercise 4: Multiple “Return” Values via References
Sometimes we have a function that we wish could return multiple values. For example, we might have a division function that should return a quotient and a remainder.
Ah, but C++ doesn't allow multiple return values!
In fact, there are ways to return multiple values, such as using
std::tuple
, a bit like you would in Python.Actually, it's really easy to use tuples in Python for multiple return values, but pretty clumsy to use them in C++.
We're really supposed to be talking about references here, but, since we've brought up
std::tuple
, the 2017 version of the C++ standard added structured bindings which makes tuples much more usable.But it's still a ton of stuff to have to learn for just the simple task of getting two distinct values out of a function. So, let's set aside that approach for now.
References can provide a simple solution to the “two return values needed” problem.
void div(size_t a, size_t b, size_t& quo, size_t& rem)
{
rem = a;
quo = 0;
while (rem >= b) {
rem = rem - b;
++quo;
}
}
int main() {
size_t x = 24;
size_t y = 7;
size_t quotient;
size_t remainder;
div(x, y, quotient, remainder);
cout << x << " " << y;
cout << " " << quotient;
cout << " " << remainder;
}
Oh, I see! You can pass in a reference to a variable and the function can fill in a value for that variable.
Now you're getting it!
References are awesome!
I know, right? It's amazing that we got this far into the semester without using them!
Okay, that was good work, but we're not done yet! Let's head back up to the parent page to see our progress and maybe take a break!
(When logged in, completion status appears here.)