Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Eraserhead

macrumors G4
Original poster
Nov 3, 2005
10,434
12,250
UK
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

macrumors 6502
Mar 31, 2005
432
0
London, England
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:

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

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

Eraserhead

macrumors G4
Original poster
Nov 3, 2005
10,434
12,250
UK
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:

Code:
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

macrumors regular
Feb 14, 2006
105
0
Another solution...

The other solution would be to create a data structure with two doubles in it. You could do something like

Code:
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

macrumors 603
Sep 19, 2003
6,056
167
Canada, eh?
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. :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.