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.
In this C++ version:
We define a
struct
calledValues
to hold multiple return values.The
vals()
function returns an instance of this struct.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.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:
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.