Returning two values at the same time in a function

3.8k Views Asked by At

How can I return two integer type values at the same time in one function in the C programming language or should I write two different functions?

5

There are 5 best solutions below

3
On BEST ANSWER

You can create a struct in which you have two integers and return this struct as the result of your function.

In a language such C, you can store your data in struct like this :

struct foo {
 int x;
 int y;
}
0
On

If return them is not mandatory and you can accept to use pointers, it follows a possible approach:

void your_function(/* some other parameters */ int *ret1, int *ret2) {
    int first_value, second_value;
    // do whatever you want there
    *ret1 = first_value; // first_value is the first value you want to return, quite obvious
    *ret2 = second_value; // still obvious
}

Then, you can invoke it as follows:

// somewhere
int r1, r2;
your_function(/* other parameters */ &r1, &r2);
// here you can use "returned" values r1, r2
0
On

In C a function can return only one value. You can pass a variable by address to the function and modify it with the function.

#include <stdio.h>

int returnTwoInt(int *var2)
{
    *var2 = 2;
    return 1;
}

int main()
{
    int var2 = 0;
    int var1 = returnTwoInt(&var2);

    printf("%d %d\n", var1, var2);

    return 0;
}
0
On

You can use either of ways -

Use struct and return struct variable .

Or

Make the function to handle the arguments with pointers.
Ex-

void f1(int *x, int *y){

*x  = 1;
*y  = 2;

 }

int main(int argc, char* argv[]) {
int x,y;
f1(&x, &y);
printf("%d %d",x,y);
return 0;
 }
2
On

Two different functions or pass by reference parameters.

e.g.

void someFunc(int* outParam1, int* outParam2)
{
    if (outParam1 != NULL) {
        *outParam1 = 42;
    }
    if (outParam2 != NULL) {
        *outParam2= 13;
    }
}