Can a function return more than one value directly (i.e., without returning in parameters taken by-reference)?
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.
No, you can not have two returns in a function, the first return will exit the function you will need to create an object.
Functions return only one value.
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 double
s 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With