How to return multiple values from a function in C

In this post, we will see how to return multiple values from a function in C.


 

We know that syntax of functions in C doesn’t allow us to return multiple values. But programmers often need to return multiple values from a functions. Luckily, there are several workarounds in C to return multiple values.

 

1. Pointers in C

We can use pointers in C to return more than one value from the function by passing pointers as function parameters and use them to set multiple values, which will then have visibility in the caller function.

Download   Run Code

Output:

a = 10, b = 20, c = A

 

2. Structures in C

We can also use structures in C to return more than one value from the function. We know that a structures is user defined datatype in C that can hold several data types of the same or different kind.

The idea is to create a struct containing all required data types as its members and return that struct from our function. Then we can retrieve the desired values from the struct inside our caller function.

 

Download   Run Code

Output:

a = 10, b = 20, c = A

 

3. Array

We have seen how to return values of different data types from the function using pointers and struts. Now if all values are of same datatype, we can encapsulate the values in an array and return that array as shown below:

 

Download   Run Code

Output:

a = 10, b = 20, c = 30

 
This approach should not be used as the variable information is not passed to the caller function. For example, we’re using array’s index to retrieve values of our variables. Also note that we have to allocate the array dynamically in heap. If we use the static array, it ceases to exist when we exit from the function and accessing it inside the caller function will result in undefined behavior.

 
Also see:

1. Return multiple values from a method in C++

2. 5 ways to return multiple values from a method in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz