How to return multiple values from a function in C programming?

return multiple value from the structure in c

Sometimes we require to return multiple values from a function in C. I found that many new programmers ask this question is because the C language does not allow to return multiple values from the function directly.

But no problem we have the way to take multiple values from the function and it is not much difficult. We can return the multiple values from the function using the pointer, array or the structure. So let see few examples to understand the concept that how to return multiple values from a function in C.

Return multiple values from the function using the array

We can return multiple values from the function using the array but the limitation is that all value should have the same type.

In the example program, I am creating an integer array of size “n” ( int ptr[n] ) and passing this integer array to the function as the parameter to collect the first to “n” odd numbers. The function parameter type could be as int ptr[] , int ptr[n] or int *ptr.

Note: For more detail, you can see how to pass an array in the function.

Output: 1 3 5 7 9 11 13 15 17 19

 

You can also use the dynamic array to return multiple values from the function. Let see one more example of how we can return multiple values using the dynamic array. If you don’t know how to create a dynamic array, please see this article to how to create a dynamic array in c.

Output: 1 3 5 7 9 11 13 15 17 19

 

If you want to learn more about the c language, here 10 Free days C video course for you.

C tutorial

Return multiple values from function – using structure

When we require to return multiple values of the different type from the function then the structure is a good choice to use. We can also do this task with the help of pointer we will see the later. A structure is a user-defined datatype, you can also see this article to understand the structure, structure in brief.

How to return multiple values from a function in C programming?

 

Return multiple values from a function in C- using the pointer

Using the call by reference we can get the multiple values from the function. Let see one example,

How to return multiple values from a function in C programming

 

3 comments

Leave a Reply