Possible Duplicate:
returning multiple values from a function
Suppose i have passed two values to a function iCalculate(int x, int y)
and this iCalculate
returns two values. Those are as follows:-
(x*y)
(x/y)
Now how should i return the above two values at the same time with the same function?
My Approach was:-
int* iCalculate(int x,int y){
int temp[2];
temp[0] = x*y;
temp[1] = x/y;
return temp;
}
returning the address of the first element of a local array has undefined behavior(at least dereferencing it later is).
You may use output parameters, that is, pass two pointers, and set the values inside
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
usage:
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, ")
Another thing you could do is pack your data into a struct
typedef struct
{
int prod;
int quot;
} product_and_quot;
product_and_quot Calculate(int x, int y)
{
product_and_quot p = {x*y, x/y};
return p;
}
That won't work, since you're returning a pointer to a temporary array, which will stop existing at function return time.
Instead, define
typedef struct { int first, second; } IntPair;
and return an object of that type.
(This is what the standard library functions div
and ldiv
do, except that they call the type differently.)
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