This post will discuss how to return multiple values from functions in C++.

We know that the syntax of a function in C++ doesn’t permit returning of multiple values. But programmers often need to return multiple values from the functions. Luckily, there are many alternatives in C++ to return multiple values.

1. Using reference parameters in C++

We have seen that we can use pointers in C to return more than one value from a function in the previous post. In C++, we have reference variables to achieve the same.

The idea is to declare the function parameters as references rather than as pointers. Now any changes made to the reference are reflected in the original variable itself. The following C++ program demonstrates it:

Download  Run Code

Output:

a = 10, b = 20, c = A

2. Using std::pair in C++

If we’re required to return only two values from the function, the recommended way is to use the std::pair. The following C++ program demonstrates it:

Download  Run Code

Output:

The returned string is A and integer is 65

3. Using std::tuple in C++11

std::pair works fine for returning two values, but it’s not flexible if we need to add more values later. From C++11 onward, we can use std::tuple that can return any number of values. The following C++ program demonstrates it:

Download  Run Code

Output:

a = 10, b = 20, c = A, d = 1.2

 
We have assigned the returned values to corresponding variables using std::tie. We can also use std::get to access tuple members.

Before C++11, the recommended alternative to std::tuple is to use Boost Tuple Library.

4. Using std::map or std::unordered_map (in C++11)

We can also use a map to return multiple values from a function, but this will work only if all values have the same data type. The following C++ program demonstrates it:

Download  Run Code

Output:

a = 10, b = 20

 
Starting from C++17, we can use Structured bindings, which offers an easier syntax to initialize values received from a pair or tuple.

That’s all about returning multiple values from functions in C++.

 
Also See:

Return multiple values from a function in C

Return multiple values from a method in Java