C / C++ FAQs & Programming Resources - ProkutFAQ : ReturningMultipleValues

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

How can we return more than one value from a function?


One simple way is to embed the different values that we want to return in a struct and then return the struct.
Example:
struct data
{
int a;
float b;
}

struct data myFunction(void)
{
struct data x;
/*set values for the members of x*/
return x;
}

int main()
{
struct data myData;
myData=myFunction();
/*Now you can access the different values within myData structure*/
return 0;
}


The other way around is to pass the pointers to different objects as argument to the function.
Suppose, you need a function fun1() to return one integer value and three float values, then, declare fun1() as:
int fun1(float *x, float *y, float *z);


Example:
int fun1(float *x, float *y, float *z)
{
int status;
/*Set the values of *x, *y, *z and status*/
return status;
}


While calling the function, pass address of three float variables in which you want to store the returned values, like:

x = fun1(&float1, &float2, &float3);


Where float1, float2, float3 are float variables and x is an integer.

References

comp.lang.c FAQ:How can I return multiple values from a function?


CategoryPointers
 Comments [Hide comments/form]
A function can return multiple result if we pass arguments one for input data and one for output data.
-- 117.200.56.218 (2009-02-21 14:08:45)
Page was generated in 0.0334 seconds