Returning more than one value from function in C

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.

Expected Output:

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.

Leave a Comment

%d bloggers like this: