Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two values from a function? [duplicate]

Tags:

c

function

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;
}
like image 884
Abhineet Avatar asked Jul 16 '11 11:07

Abhineet


2 Answers

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;
}
like image 116
Armen Tsirunyan Avatar answered Oct 12 '22 18:10

Armen Tsirunyan


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

like image 24
Fred Foo Avatar answered Oct 12 '22 18:10

Fred Foo