You can't return two values. However, you can return a single value that is a struct that contains two values.
Answer from Ted Hopp on Stack OverflowYou can't return two values. However, you can return a single value that is a struct that contains two values.
You can return only one thing from a function. Either you make a struct which contains all the things you want to return, or you pass some function parameters by reference.
Hello developers, I want to know about how can I return multiple values from a function. I have read few articles but still confused.
Videos
It's not a sign of anything, and is not neither good nor bad design or coding style.
Returning multiple values can actually be appropriate and allow to write less code. Let's take an example of a method which takes a string like "-123abc" and converts it to an integer like -123:
(bool, int) ParseInteger(string text)
{
// Code goes here.
}
returns both:
- a value indicating whether the operation was a success,
- the number converted from string.
How can we refactor this?
1. Exceptions
We can add exceptions, if the language supports them. Remember than in most languages, exceptions are expensive in resources. It means that if you have to deal with lots of non-numbers, it's better to avoid to throw an exception every time the string cannot be converted to a number.
2. New class
We can create a class and return an instance of an object of this class.
For example:
class ParsedInteger
{
bool IsSuccess { get; set; }
int Number { get; set; }
}
Is it easier to understand? Shorter to write? Does it bring anything? I don't think so.
3. Out parameters
If the language supports it, we can also use out parameters. This is the approach of C# where returning multiple values is not possible. For example, when parsing a number, we use: bool isSuccess = int.TryParse("-123abc", out i). I'm not sure how is it better to use out parameters compared to multiple values. The syntax is not obvious, and even StyleCop itself (the tool used to enforce the default Microsoft style rules on the code) complains about those parameters, suggesting to remove them when possible.
Finally, in languages as C# where there is no such a thing as returning multiple values, things are progressively added to imitate the behavior. For example, Tuple was added to allow returning several values without having to write your own class or use out parameters.
When your function returns a reference to an object that contains multiple members, is it returning one value or many? In the example you show, the function is actually returning an object of type tuple. Python just happens to support syntactic 'sugar' so that you don't have to explicitly dereference the members when making assignments from the return value of the function.
In the boost::tuple library, there's a function called tie that simplifies the process of getting information out of a returned tuple. If you had a function that returned a tuple of two doubles and wanted to load those into two local variables x and y, you could assign your function's return value to boost::tie(x, y).
Example:
#include <math.h>
#include <iostream>
#include <boost/tuple/tuple.hpp>
const double PI = 3.14159265;
boost::tuple<double, double> polar_to_rectangular(double radius, double angle)
{
return boost::make_tuple(radius * cos(angle), radius * sin(angle));
}
int main()
{
double x;
double y;
boost::tie(x, y) = polar_to_rectangular(4, (45 * PI) / 180);
std::cout << "x == " << x << ", y == " << y << std::endl;
return 0;
}
Yes - have your function return a struct. Or return the values via reference parameters.
struct A {
int x, y;
A(int x, int y) : x(x), y(y) {}
};
A myfun() {
return A(0, 42); // return two values
}
or:
void myfun(int & a, int & b) {
a = 0;
b = 42;
}
Push them onto the stack
This really only applies to stack-based languages, and perhaps Assembly. The good thing about this approach is that its somewhat more natural to work with the returned values. If you do divmod, you can pop once to get the quotient, pop the next element to get the remainder. The downside is that if you want to call a function that returns multiple values and immediately pass them on, it might be a bit cumbersome, depending on the language.
Custom types
In languages such as Java and Kotlin, which really love their nominal typing, you would make a new class specific to that one function. For example, divmod might return a DivmodResult object with fields quotient and remainder (Kotlin does have a Pair class in its standard library, but it's dropped actual tuples now).
Advantages:
- When you have to return 4 or more values, it really helps to have a class specifically for that purpose if you have a statically typed language. I'd rather see a return type of
FooResultthan some enormous tuple like(int, String, BarProducer, String, int)
Disadvantages:
- Making a whole class for a single function is annoying. Some languages do have syntactic sugar for this (e.g.
data classin Kotlin) but it's so much easier to use something like tuples or lists instead. In Java, you'll have to make getters and setters and constructors for a minor class that might only be used in one or two places.