0

Is it possible to create a function and do multiple calculations in that function, then create another function to print out the results of the calculations... I know a function can only return one value.

3 Answers3

4

There are several ways to return multiple values. One way is to "package" them as a struct:

typedef struct
{
  int x;
  float y;
} Result;

Result add2( int x1, int x2, float y1, float y2)
{
  Result r;
  r.x = x1 + x2;
  r.y = y1 + y2;
  return r;
}

Another way to do it is to use parameters as your outputs:

void add2( int x1, int x2, float y1, float y2, int* x, float* y)
{
  *x = x1 + x2;
  *y = y1 + y2;
}

You could also do combinations of these.

Stewart
  • 4,356
  • 2
  • 27
  • 59
  • You need a `typedef` in order to use `Result` without the `struct` keyword. – David Ranieri May 29 '17 at 20:13
  • That's a good example, but when all the fields in the `struct` are of the same type, you could achieve the same by using an array. A better example (more general one) is if they were of different types. – SHG May 29 '17 at 20:13
  • @SHG: Just because you *can* achieve the same result with an array, doesn't mean it's preferable to. A two-dimensional coordinate value, for example, would be better represented as a `struct` than as a two-element array. And obviously you can't return an array from a function, so if you wanted to do this, you'd still need to wrap it in a `struct`. – Crowman May 29 '17 at 20:17
  • @PaulGriffiths Right. I didn't say it's preferable, just that you can. And if you show an example for a concept, make it general. Obviously one of the advantages of a struct would be to be able to return different types, so it's better to be demonstrated as well. – SHG May 29 '17 at 20:21
3

One return value is for wimps! Simply define the function as

struct retval { int i; double d; size_t z; } func(void);

(replacing the contents of the struct and the parameters as applicable).

Be careful when doing this, though. In spite of what I said up top, in general there is no need for multiple returns.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Gold Dragon
  • 480
  • 2
  • 9
1

You can create a struct with all the things ​​you are interested in, alloc it on heap, edit it inside a function, return the same struct that you have edited and at the end free the memory. Alternatively, you can also pass the pointer and at the end free the memory.

Example:

typedef struct date_test {
int year;
int month;
int day;
} Date;

With this you create a structure that will contain 3 int values: year, month and day.

Alloc it on heap and check for errors:

Date *test = malloc(sizeof(Date));
if (test == NULL) {
    perror("Malloc");
    exit(EXIT_FAILURE);
}

Edit it inside a function and return the struct, example:

Date* test_f(Date* test)
{
    test->year = 2017;
    test->month = 05;
    test->day = 29;
    return test;
}

Then free the allocated memory:

free(test);
Overflow 404
  • 482
  • 5
  • 20