how to return more than one value from a function?
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.
2 Comments
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.
Comments
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);