Return two values (doubles) from a C function

Discussion in 'Mac Programming' started by Eraserhead, Feb 8, 2007.

  1. macrumors G4

    Eraserhead

    #1
    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?
     
  2. macrumors 6502

    #2
    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;
    }
    
     
  3. macrumors G4

    Eraserhead

    #3
    I was missing the *doubleRef in the function, now that's sorted it works thanks!
     
  4. macrumors regular

    #4
    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.
     
  5. macrumors 603

    notjustjay

    #5
    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. :)
     

Share This Page