CS 70

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.

  • Duck speaking

    Ah, but C++ doesn't allow multiple return values!

  • Bjarne speaking

    In fact, there are ways to return multiple values, such as using std::tuple, a bit like you would in Python.

  • Python speaking

    Actually, it's really easy to use tuples in Python for multiple return values, but pretty clumsy to use them in C++.

  • LHS Cow speaking

    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.

  • RHS Cow speaking

    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;
}

Draw a memory diagram of the execution of this program and then give the printed output.

  • Cat speaking

    Oh, I see! You can pass in a reference to a variable and the function can fill in a value for that variable.

  • LHS Cow speaking

    Now you're getting it!

  • Dog speaking

    References are awesome!

  • LHS Cow speaking

    I know, right? It's amazing that we got this far into the semester without using them!

  • RHS Cow speaking

    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.)