How to return two values from a function?

The way you did is wrong since int temp[2] disappears once the function returns, so the caller has a "dangling" pointer. You have to add static. Another way, likely better, is to let the caller pass where it wants the result be store e.g.

void iCalc(int x, int y, int *rp, int *rq)
{
   // check if rp and rq are NULL, if so, returns
   *rp = x*y;
   *rq = x/y; // y != 0, and this will truncate of course.
}

and the caller will do something like

int res[2];
iCalc(x, y, res, res+1);

or similar.


Your approach is wrong, temp is out of scope/ not longer exist when functon iCalculate exit. So you must not return the address of temp. That would be address of out of scope/ no longer exist variable. Accessing that address means undefined behaviour.

You can use this approach:

void iCalculate(int x,int y,int *mult,int *divi){
   *mult = x*y;
   *divi = x/y;
}

or you can use another approach:

typedef struct{ 
   int mul, divi;
} TResult;

TResult iCalculate(int x,int y){
   TResult res;
   res.mul = x*y;
   res.divi = x/y;
   return res;
}

or :

void iCalculate(int x,int y,TResult *res){
   res->mul = x*y;
   res->divi = x/y;
}

I suggest the first approach. I think it is too silly to create a new struct definition only to wrap 2 unrelated value together.


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


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, &quot)

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;
}

Tags:

C

Function