Trusted answers to developer questions

How to return multiple values from a function in C++17

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

While C++ does not have an official way to return multiple values from a function, one can make use of the std::pair, std::tuple, or a local struct to return multiple values.

However, with the introduction of structured binding in C++17, the process is greatly simplified as the output parameters no longer need to be initialized.

svg viewer

Code

The following code snippet shows the way to return multiple values from a function using a local structure:

#include <iostream>
using namespace std;
auto foo() {
struct retVals { // Declare a local structure
int i1, i2;
string str;
};
return retVals {10, 20, "Hi"}; // Return the local structure
}
int main() {
auto [value1, value2, value3] = foo(); // structured binding declaration
cout << value1 << ", " << value2 << ", " << value3 << endl;
}

Note the structured binding syntax on line 1313; there is no need to instantiate output values before calling the function. The datatypes are determined automatically.

The std::tuple can also be used to return multiple values in conjunction with structured binding. This is shown below:

#include <iostream>
#include <tuple>
using namespace std;
tuple<int, float, string> foo()
{
return {128, 3.142, "Hello"};
}
int main()
{
auto [value1, value2, value3] = foo();
cout << value1 << ", " << value2 << ", " << value3 << endl;
}

RELATED TAGS

c++17
multiple values
return
function
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?