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.
For returning two values I use a std::pair
(usually typedef'd). You should look at boost::tuple
(in C++11 and newer, there's std::tuple
) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple
should probably become accepted standard.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments