OverIQ.com

Returning more than one value from function in C

Last updated on July 27, 2020


In the chapter Return statement in C, we have learned that the return statement is used to return a value from the function. But there is one limitation, a single return statement can only return one value from a function. In this chapter, we will see how to overcome this limitation by using call by reference.

Consider the following problem.

Q - Create a function to return sum, difference and product of two numbers passed to it.

Tell me how would you approach this problem?

One way to approach this problem is to create three functions for 3 operations and then use the return statement in each one of them to return sum, difference and product. By using call by reference we can solve this much easily.

The following program demonstrates how you can return more than one value from a function using call by reference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<stdio.h>
void return_more_than_one(int a, int b, int *sum, int *diff, int *prod);

int main()
{
    int x = 40, y = 10, sum, diff, prod;

    return_more_than_one(x, y, &sum, &diff, &prod);

    printf("%d + %d = %d\n",x, y, sum);
    printf("%d - %d = %d\n",x, y, diff);
    printf("%d * %d = %d\n",x, y, prod);

    // signal to operating system program ran fine
    return 0;
}

void return_more_than_one(int a, int b, int *sum, int *diff, int *prod)
{
    *sum = a+b;
    *diff = a-b;
    *prod = a*b;
}

Expected Output:

1
2
3
40 + 10 = 50
40 - 10 = 30
40 * 10 = 400

How it works:

In return_more_than_one() function a and b are passed using call by value, whereas sum, diff and prod are passed using call by reference. As a result return_more_than_one() function knows the address of sum, diff and prod variables, so it access these variables indirectly using a pointer and changes their values.