Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function return more than one value? [duplicate]

Can a function return more than one value directly (i.e., without returning in parameters taken by-reference)?

like image 459
Ashish Yadav Avatar asked Apr 03 '10 16:04

Ashish Yadav


People also ask

Can functions return more than 1 value?

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.

Can you return 2 values from a function?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

How many return values can a function have?

Functions return only one value.


1 Answers

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;
}
like image 101
Josh Townzen Avatar answered Sep 20 '22 15:09

Josh Townzen