Back To Basics: Returning multiple variables from functions

How can i....

An interesting issue many new programmers come up against when first getting their feet wet is the scenario of implementing a function that either MUST return multiple variables, or would greatly benefit from doing so. Though their are many ways to accomplish this, some better than others none of them are very intuitive to the new comer.

While its true that some languages have implemented this directly (Swift, python), some languages require a bit more imagination (C), or a rather better knowledge of the standard library than a beginner might know.

What follows is a a couple of methods for handling this scenario in C/C++.

Method one: (C/pre-98 C++) struct

If you need to return several values of different types the "C way" to do this is to wrap them in a struct and return the struct. For example, lets say you have a function that takes, 2 ints, and from that function, you would like to get back a double and a string:

 

Method Two: (C++17) std::pair

std::pair is a container class in the C++ STL, it is in fact a generic implementation of exactly what we did above, except standardized

The std::pair type can be thought of something looking like this:

namespace std {

template <class T1, class T2>

struct pair {

    T1 first;

    T2 second;

  };

}

While not an exact implementation, you get the idea. combined with std::make_pair() we have a convenient way of returning values of different types from a function.

 

Keep in mind that the above code is C++17 compatible, but not viable in C++11 or below, for C++11 you can substitute auto boxing with std::tie(). The better option is to use --std=c++17 (or c++2a)

Method Three: (C++17) std::tuple

Functionally similar to std::pair, std::tuple works in the same manner with the exception that it allows us to return more than two values, without having to do something insane like std::pair<std::pair<int, double>, std::pair<string, float> >, because that kind of code is the stuff of nightmares. std::pair is in actuality a wrapper around std::tuple.

Wrapping Up

So there you have at three methods to return multiple values of different types from a function. Keep in mind that the first option is valid in both C and classical C++, while all three methods will work in Modern C++. If you're using C++ you should probably stick to one of the second two solutions.


Leave A Comment