Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Returning 2 values in a function and trying to use them

Tags:

c

So I have this function where I return 2 values:

return result, result2;

Now what I am trying to do is use these 2 values in my main function. I want to save it into a variable in main function like this :

variable = function(a,b);

But how do you specify here which value you want?

like image 420
Kaspar Avatar asked Jan 30 '14 16:01

Kaspar


People also ask

Can I return 2 values from a function in C?

In C or C++, we cannot return multiple values from a function directly.

Can we use 2 return in a function?

Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables.

How do I store two values returned from a function?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

How do you use a returned value from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.


1 Answers

No, you cannot do this in C, you can just return one value. The comma operator returns just the last value, so you are actually returning the second one.

You can pass data by reference, like

function(&a, &b);

void function(int *a, int* b){
    *a = 42;
    *b = 666;
}

You can also put them in a structure and return it or even a pointer to a dynamically allocated structure.

typedef struct int_pair {
    int a, b;
} int_pair;

int_pair function(){
    int_pair s;

    s.a = 42;
    s.b = 666;

    return s;
}
like image 64
fede1024 Avatar answered Sep 28 '22 08:09

fede1024