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.
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.
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.
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.
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.
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