Is there a way to get more than one value from a function. Presently function just return one value as specified in its return type.
Printable View
Is there a way to get more than one value from a function. Presently function just return one value as specified in its return type.
You can pass in pointers or references to functions. These can be used to return information to the caller.
For example:
You'll notice that FirstParam is passed by reference, and SecondParam is passed as a pointer.Code:
// some routine
{
int FirstParam = 0;
int SecondParam = 0;
MultipleReturns(FirstParam, &SecondParam);
printf("FirstParam = %d, SecondParam = %d\n", FirstParam, SecondParam);
}
// The function returning more than one thing
void MultipleReturns(int & First, int *Second)
{
First = 21;
*Second = 45;
}
Just for grins, I declared the routine void (no return value).
Hope this helps,
- Nigel
Thaknks for your advise. I am able to get the values as I wanted it to be.
You can also return 2 values by using std::pair< T1, T2 > where T1 and T2 are the types.
Any more and you can always put them into a struct and return the struct.
The other option, as been mentioned above, is for the function to take non-const references (or pointers) and write the values into there.
If there are a lot of variables let's say int
int MyArray[10];
you can send int* MyArray as an argument to the function and then access the whole array by reference.
Ted
Another option is to try boost::tuple.
What do you mean exactly? I've never heard of this.Quote:
Originally Posted by KevinHall
Boost is a library of features that people hope will be added to the C++ standard. Actually, there's more to it than that, but I digress. So you can view boost as a free addon library.
Anyway, here is the documentation for boost::tuple.