how to return more than one value from a function?
-
3Many duplicates on SO already, for C, C++ and other languages, e.g. [can a function return more than one value?](http://stackoverflow.com/questions/2571831/can-a-function-return-more-than-one-value) – Paul R Jan 02 '11 at 15:31
5 Answers
A function can only have a single return value. You could either pack multiple values into a compound data type (e.g. a struct), or you could return values via function parameters. Of course, such parameters would have to be passed using pointers to memory declared by the caller.

- 601,492
- 42
- 1,072
- 1,490
1
Declare method like this foo (char *msg, int *num, int *out1, int *out2);
and call it like this
int i=10;
char c='s';
int out1;
int out2;
foo(&c,&i,&out1,&out2);
Now what ever values u assign to out1 and out2 in function will be available after the function returns.
2
Return a structure having more than one members.

- 1
- 1

- 5,994
- 7
- 46
- 69
In C, one would generally do it using pointers:
int foo(int x, int y, int z, int* out);
Here, the function returns one value, and uses out
to "return" another value. When calling this function, one must provide the out
parameter with a pointer pointing to allocated memory. The function itself would probably look something like this:
int foo(int x, int y, int z, int* out) {
/* Do some work */
*out = some_value;
return another_value;
}
And calling it:
int out1, out2;
out1 = foo(a, b, c, &out2);

- 22,800
- 3
- 51
- 64
You cannot return more than 1 value from a function. But there is a way. Since you are using C, you can use pointers.
Example:
// calling function:
foo(&a, &b);
printf("%d %d", a, b);
// a is now 5 and b is now 10.
// called function:
void foo(int* a, int* b) {
*a = 5;
*b = 10;
}

- 6,018
- 4
- 27
- 45