Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

Possible Duplicate:
can a function return more than one value?

I want to return 3 variables from a c++ function but as one function can have only one running return value how I can return 3 values. tried using return(5,4); but this is an syntax error.

like image 537
Sudhir Chopra Avatar asked Jun 18 '11 08:06

Sudhir Chopra


4 Answers

A C++ function can return only one value. However, you can return multiple values by wrapping them in a class or struct.

struct Foo
{
     int value1;
     int value2;
};

Foo SomeFunction()
{
    Foo result = { 5, 4 };
    return result;
}

Or you could use std::tuple, if that is available with your compiler.

#include <tuple>

std::tuple<int, int, int> SomeFunction()
{
    return std::make_tuple(5, 4, 3);
}

If you don't know in advance how many values you're going to return, a std::vector or a similar container is your best bet.

You can also return multiple values by having pointer or reference arguments to your function and modifying them in your function, but I think returning a compound type is generally speaking a "cleaner" approach.

like image 88
Sven Avatar answered Dec 26 '22 10:12

Sven


You can only return one value in C++. If you need to return more information, return a structure (or a container like a std::vector for example), or pass in some variables as non-const references (or pointers) and change those.

like image 35
Mat Avatar answered Dec 26 '22 10:12

Mat


tried using return(5,4); but this is an syntax error.

That is not a syntax error. (5,4) is a valid expression and here , is an operator. So the expression (5,4) evaluates to the rightmost operand, which is 4. Hence it will return 4.


Now coming to your problem: define a struct if any existing one doesn't help you, and return an object of struct instead, as:

struct values
{
   int i;
   int j;
   char *other;
};

values f()
{
  values v = {/*....*/};
   //...
   return v;
}

And if type of all values is same, then you can use std::vector as:

#include <vector>  //must include it!

std::vector<int> f()
{
   std::vector<int> v;
   v.push_back(5);
   v.push_back(4);
   //so on
   //...
   return v;
}

There are other containers as well, viz. std::map, std::list, std::stack, etc. Use which suits you the best. There is also std::pair which holds only two values, as the name implies.

like image 35
Nawaz Avatar answered Dec 26 '22 11:12

Nawaz


Or you could use std::pair for two results and look at boost::tuple for more than two. It can even handle different types in the same tuple.

like image 32
luvieere Avatar answered Dec 26 '22 09:12

luvieere