Returning several values from a function in C++ (C++23 edition) -- Daniel Lemire
While C++ doesn’t have native syntax for returning multiple values like some other languages, modern C++ offers powerful tools to accomplish the same goal. With features like
std::tuple
, structured bindings, std::expected
, and std::optional
, handling multiple return values—and even error codes—has become both clean and expressive.
Returning several values from a function in C++ (C++23 edition)
by Daniel Lemire
From the article:
Many programming languages such as the Go programming language are designed to make it easy to return several values at once from a function. In Go, it is often used to return an optional error code. The C++ programming language does not have a built-in support for returning several values. However, several standard types can serve the same purpose. If you need to return two values, you can use an std::pair instance. If you need to return two or more values, an std::tuple instance will do. With recent C++ standards, it works really well!
Suppose we want to compute a division with a string error message when one is trying to divided by zero:
std::tuple<int,std::string> divide(int a, int b) { if (b == 0) { return {0, "Error: Division by zero"}; } return {a / b, "Success"}; }This approach works nicely. The code is clear and readable.
You might be concerned that we are fixing the type (int). If you want to write one function for all integer types, you can do so with concepts, like so: