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. Commented 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. Commented Mar 14, 2013 at 17:15
  • 1
    why don't you just make two different functions? Commented Mar 14, 2013 at 17:17
  • @Zupoman: Floor is already a different function. Commented 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 );
Sign up to request clarification or add additional context in comments.

1 Comment

your code works perfectly..
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 Comments

Pass by reference you mean.
You need to have struct ab ab_instance.
@meyumer i have used the second example : pass by reference and i call the function : long b; long a=Conv(30.233456,&b);
@meyumer : invalid initialization of non-const reference of type 'long int&' from a temporary of type 'long int*'
@meyumer error: in passing argument 2 of 'long int Conv(double, long int&)'
|
1

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

int get_both(int* b) {
    a = 0;
    *b = 1;
    return a;
}

3 Comments

long Conv(double num){ long a,b; a = floor(num); *b = num * pow(10,6) - a * pow(10,6); return a; }
i tried something like this but gives me error
Where is the error, and what is it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.