Returning multiple values from a C++ function

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:

void divide(int dividend, int divisor, int& quotient, int& remainder);

A variation is to return one value and pass the other through a reference parameter:

int divide(int dividend, int divisor, int& remainder);

Another way would be to declare a struct to contain all of the results and return that:

struct divide_result {
    int quotient;
    int remainder;
};

divide_result divide(int dividend, int divisor);

Is one of these ways generally preferred, or are there other suggestions?

Edit: In the real-world code, there may be more than two results. They may also be of different types.

23 Answers
23

Leave a Comment