2

I made a function, and I want to retrieve two returns, not a single return such as this example:

long Conv(double num){      
    long a,b;
    a = floor(num);
    b = num * pow(10,6) - a * pow(10,6);

    return a;
    return b;
} 

When I call the function

long a = Conv(30.233456);

the question is: how do I retrieve b?

4
  • 3
    Return a struct with both values in it, or have your function take pointers to a and b and write the values there.
    – gspr
    Mar 14, 2013 at 17:15
  • Just use floor(num) to get a (if you need it outside the function), and return b from your function. If you only want to calculate a once, pass it into the function as a parameter. Mar 14, 2013 at 17:15
  • 1
    why don't you just make two different functions?
    – pampeho
    Mar 14, 2013 at 17:17
  • @Zupoman: Floor is already a different function. Mar 14, 2013 at 17:18

3 Answers 3

4

You can't return two times at once.

You could pass b to your function by reference.

yourfunction( long a , long* b )
{    
    *b = a + 10;
    //more code

return a;
}

a = yourfunction(a , &b );
1
  • your code works perfectly.. Dec 4, 2018 at 13:43
3

You can't return more than one value from a function in C. Either return a struct, or pass by reference and modify in the function.

Example 1: struct

struct ab {
  long a;
  long b;
}

struct ab Conv(double num) {
  struct ab ab_instance;

  ab_instance.a = floor(num);
  ab_instance.b = num * pow(10,6) - a * pow(10,6);

  return ab_instance;
}

Example 2: pass b by reference

long Conv(double num, long& b) {
  long a;
  a = floor(num);
  b = num * pow(10,6) - a * pow(10,6);

  return a;
}
7
  • 1
    Pass by reference you mean.
    – gspr
    Mar 14, 2013 at 17:16
  • You need to have struct ab ab_instance.
    – gspr
    Mar 14, 2013 at 17:19
  • @meyumer i have used the second example : pass by reference and i call the function : long b; long a=Conv(30.233456,&b); Mar 14, 2013 at 17:37
  • @meyumer : invalid initialization of non-const reference of type 'long int&' from a temporary of type 'long int*' Mar 14, 2013 at 17:38
  • @meyumer error: in passing argument 2 of 'long int Conv(double, long int&)' Mar 14, 2013 at 17:39
1

Armin kind of answered it, but here is some sample code:

int get_both(int* b) {
    a = 0;
    *b = 1;
    return a;
}
3
  • long Conv(double num){ long a,b; a = floor(num); *b = num * pow(10,6) - a * pow(10,6); return a; } Mar 14, 2013 at 17:26
  • i tried something like this but gives me error Mar 14, 2013 at 17:27
  • Where is the error, and what is it? Mar 14, 2013 at 17:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.