HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Returning multiple values from a C++ function

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromfunctionmultiplevaluesreturning

Problem

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.

Solution

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.

Context

Stack Overflow Q#321068, score: 290

Revisions (0)

No revisions yet.