# Thread: Return Variable

1. ## Return Variable

Hi There,

I'm new with C, and trying to learn it on school. We have to do a little project on our own and my question is:

Is it possible to have more then 1 return variable in a function.

I'd like to create a function that has 3 inputs and 2 outputs, but i cant find it in my book.

I hope you can answer my question

- SpoiLeD

2. could you able to give a little bit more explanation ?

i cant really figure out what they mean.

- The global variable is not working for me, because the variable changes in the function.

- SpoiLeD

3. Using global variables:
Code:
```int x, y, z;

void f();

int main(void)
{
f();
printf("f() returned %d, %d, %d via globals\n",x,y,z);
return 0;
}

void f()
{
x = 3;
y = 4;
z = 5;
}```
Above, the function f() effectively returns values by changing global variables. This is the stupidest method possible.

Using a struct:
Code:
```struct foo { int x, y, z; };

struct foo f();

int main(void)
{
struct foo bar;
bar = f();
printf("f() returned %d, %d, %d via a struct\n",bar.x, bar.y, bar.z);
return 0;
}

struct foo f()
{
struct foo t;
t.x = 3; t.y = 4; t.z = 5;
return t;
}```
Above, f() returns a struct, containing 3 fields.

Using pointers:
Code:
```void f(int *, int *, int *);

int main(void)
{
int a, b, c;
f(&a, &b, &c);
printf("f() returned 3 values using pointers: %d, %d, %d\n", a,b,c);
return 0;
}

void f(int *x, int *y, int *z)
{
*x = 3; *y = 4; *z = 5;
}```
Above, f() is passed the addressed of each variable in main, and sets them by dereferencing.

4. i do not understand what u want exactly from these statements:

>>Is it possible to have more then 1 return variable in a function. (Explain more)

>>I'd like to create a function that has 3 inputs and 2 outputs, but i cant find it in my book. (explain more)

maybe the following code might help:

Code:
```#include <stdio.h>

int returnf(int a, int b, int c) { // function takes three inputs but returns one variable depending on which is zero

if(a == 0 || b == 0) // to check if either the 1st or second argument is zero
return a;

else
return b;

}

void main(void) {
printf("function returns: %i bcoz either a or b is zero\n", returnf(2, 0, 5));

printf("function returns: %i\n", returnf(0, 4, 1));

printf("function returns: %i", returnf(5, 5, 1));

getchar();
}```
Any further questions? Glad 2 be of service...

5. sidideas,

The original question is quite clear, they want to return several values. A function only ever returns one type, but multiple values can be simulated using the methods I described above.

6. Thank you very much cwr for helping

I do understand it now by those examples..

And now the program works by using the pointers

Thanks!

- SpoiLeD

Popular pages Recent additions