How to return multiple values from functions in C++

In this post, we will see how to return multiple values from functions in C++.

 
We know that syntax of a function in C++ doesn’t permit to return 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. Here is C++ program to demonstrate 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 std::pair. Here’s a C++ program to demonstrate it:

 

Download   Run Code

Output:

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. Here’s C++ program to demonstrate 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. Here’s C++ program to demonstrate 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.

 
Also see:

1. Return multiple values from a method in C

2. 5 ways to return multiple values from a method in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz