Multiple Return Values in C++

Multiple return values are not directly supported in C++, but we can achieve similar functionality using structures, tuples, or by passing references. In this example, we’ll use a struct to return multiple values.

#include <iostream>
#include <tuple>

// We define a struct to hold multiple return values
struct Values {
    int a;
    int b;
};

// This function returns a struct containing two integers
Values vals() {
    return {3, 7};
}

int main() {
    // We use structured binding (C++17 feature) to unpack the returned values
    auto [a, b] = vals();
    std::cout << a << std::endl;
    std::cout << b << std::endl;

    // If you only want a subset of the returned values,
    // you can ignore some values using structured binding
    auto [_, c] = vals();
    std::cout << c << std::endl;

    return 0;
}

In this C++ version:

  1. We define a struct called Values to hold multiple return values.

  2. The vals() function returns an instance of this struct.

  3. In the main() function, we use structured binding (a C++17 feature) to unpack the returned values. This is similar to multiple assignment in other languages.

  4. To ignore a value, we use the underscore _ in the structured binding, which is similar to using the blank identifier in some other languages.

To compile and run this program:

$ g++ -std=c++17 multiple_return_values.cpp -o multiple_return_values
$ ./multiple_return_values
3
7
7

Note that C++ doesn’t have built-in support for multiple return values like some other languages, but we can achieve similar functionality using these techniques. The use of structs or tuples for multiple returns is a common idiom in C++ programming.

C++ also supports other ways of returning multiple values, such as using std::tuple or passing arguments by reference, which can be explored for more advanced use cases.