If I have a function that produces a result int
and a result string
, how do I return them both from a function?
As far as I can tell I can only return one thing, as determined by the type preceding the function name.
If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.
You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.
A function in C can return only one value.
I don't know what your string
is, but I'm going to assume that it manages its own memory.
You have two solutions:
1: Return a struct
which contains all the types you need.
struct Tuple { int a; string b; }; struct Tuple getPair() { Tuple r = { 1, getString() }; return r; } void foo() { struct Tuple t = getPair(); }
2: Use pointers to pass out values.
void getPair(int* a, string* b) { // Check that these are not pointing to NULL assert(a); assert(b); *a = 1; *b = getString(); } void foo() { int a, b; getPair(&a, &b); }
Which one you choose to use depends largely on personal preference as to whatever semantics you like more.
Option 1
: Declare a struct with an int and string and return a struct variable.
struct foo { int bar1; char bar2[MAX]; }; struct foo fun() { struct foo fooObj; ... return fooObj; }
Option 2
: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:
int fun(char **param) { int bar; ... strcpy(*param,"...."); return bar; }
or
char* fun(int *param) { char *str = /* malloc suitably.*/ ... strcpy(str,"...."); *param = /* some value */ return str; }
Option 3
: Similar to the option 2. You can pass both via pointer and return nothing from the function:
void fun(char **param1,int *param2) { strcpy(*param1,"...."); *param2 = /* some calculated value */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With