PDA

View Full Version : Return two values (doubles) from a C function




Eraserhead
Feb 8, 2007, 11:49 AM
I know I'm being really dumb here, but what's the best way of returning two numbers from a C-function back to the main method?



Nutter
Feb 8, 2007, 12:17 PM
There's no way to return more than one value.

The solution is to pass a pointer to a variable into your function, and set the value at that address in the function.

For example:


void main()
{
double firstDouble, secondDouble;
firstDouble = function(&secondDouble);
// etc.
}

double function(double *doubleRef)
{
*doubleRef = 2.0;
return 1.0;
}

Eraserhead
Feb 8, 2007, 12:25 PM
There's no way to return more than one value.

The solution is to pass a pointer to a variable into your function, and set the value at that address in the function.

For example:


void main()
{
double firstDouble, secondDouble;
firstDouble = function(&secondDouble);
// etc.
}

double function(double *doubleRef)
{
*doubleRef = 2.0;
return 1.0;
}


I was missing the *doubleRef in the function, now that's sorted it works thanks!

mbabauer
Feb 8, 2007, 12:45 PM
The other solution would be to create a data structure with two doubles in it. You could do something like

typedef struct {
double one;
double two;
} DoubleDouble;

I am a little rusty at C, but this is the basic idea and should work. In this case, you would get a reusable structure type defined to DoubleDouble.

notjustjay
Feb 8, 2007, 12:48 PM
From a semantics point of view, I would prefer to pass both variables by reference, or return a struct containing the two, rather than return one and pass the other by reference. It just seems cleaner this way.

Heh, DoubleDouble. That's how I take my coffee. :)