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?
Returning two values at the same time in a function
3.8k Views Asked by eestudent At
5
There are 5 best solutions below
0

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

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;
}
You can create a
struct
in which you have two integers and return thisstruct
as the result of your function.In a language such C, you can store your data in
struct
like this :