Is it possible to return 2 variables for ex.
Code:int hello(int x, int y)
{
x++;
y++;
return x,y;
}
Printable View
Is it possible to return 2 variables for ex.
Code:int hello(int x, int y)
{
x++;
y++;
return x,y;
}
Example:
Code:void hello(int &x, int &y) {
x++;
y++;
}
No. But you can wrap them up in a struct and then return the struct.
Code:struct Return2Ints {
int x;
int y;
};
Return2Ints hello (int x, int y)
{
return Return2Ints(x+1,y+1);
}
how would i recieve it?
xbeing a struct?Code:x = return2numbers();
From Thantos' example:
Code:Return2Ints someStruct = hello (1,2);
Adding to bithub:
To get to the actual values
Code:int a = someStruct.x;
int b = someStruct.y;
A generic way to do this is to return an std::pair:
std::pair<int,int> hello(int x, int y); { return std::make_pair (x,y); }
std::pair bla = hello(1,2);
cout << bla.first; //x
Tuples (look up Boost.Tuple) let you return any number of values. You can use Boost.Tuple in a similar way to std::pair.
>> return Return2Ints(x+1,y+1);
Return2Ints needs a proper constructor for that to work.
ggCode:struct Return2Ints {
int x;
int y;
Return2Ints(int x_, int y_) : x(x_), y(y_) {}
};
Opps forgot about that. Though it can be done without a constructor:
Code:Return2Ints hello(int x, int y)
{
Return2Ints ret = {x+1,y+1};
return ret;
}
Added part in red above.Quote:
Originally Posted by azteched