Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return multiple values from a function in C?

Tags:

c

return-value

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.

like image 249
Tony Stark Avatar asked Apr 12 '10 06:04

Tony Stark


People also ask

Can we return multiple values from a function?

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.

How can I return multiple values?

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.

How many values can a function return in C?

A function in C can return only one value.


2 Answers

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.

like image 150
Travis Gockel Avatar answered Oct 10 '22 21:10

Travis Gockel


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 */ } 
like image 38
codaddict Avatar answered Oct 10 '22 20:10

codaddict