This post will discuss how to return multiple values from a function in C.

We know that the syntax of functions in C doesn’t allow us to return multiple values. But programmers often need to return multiple values from a function. 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 structure is a 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 the same data type, 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

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

That’s all about returning multiple values from a function implementation in C.

 
Also See:

Return multiple values from functions in C++

Return multiple values from a method in Java