0

how to return more than one value from a function?

1

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Check out the concept of reference parameters. That may help
@programmer this is C rather than C++
2

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

1

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); 

Comments

1

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; } 

Comments

0

Functions can return arrays or lists

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.