Open In App

How to return multiple values from a function in C or C++?

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
83 Likes
Like
Report

New programmers are usually in the search of ways to return multiple values from a function. Unfortunately, C and C++ do not allow this directly. But fortunately, with a little bit of clever programming, we can easily achieve this. Below are the methods to return multiple values from a function in C:

  1. By using pointers.
  2. By using structures.
  3. By using Arrays.

Example: Consider an example where the task is to find the greater and smaller of two distinct numbers. We could write multiple functions. The main problem is the trouble of calling more than one functions since we need to return multiple values and of course, having more number of lines of code to be typed.

  1. Returning multiple values Using pointers: Pass the argument with their address and make changes in their value using pointer. So that the values get changed into the original argument. 
C++
C
Output:
Enter two numbers: 
5 8
The greater number is 8 and the smaller number is 5
  1. Returning multiple values using structures : As the structure is a user-defined datatype. The idea is to define a structure with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. 
Output:
Enter two numbers: 
5 8
The greater number is 8 and the smaller number is 5
  1. Returning multiple values using an array (Works only when returned items are of same types): When an array is passed as an argument then its base address is passed to the function so whatever changes made to the copy of the array, it is changed in the original array. Below is the program to return multiple values using array i.e. store greater value at arr[0] and smaller at arr[1]. 
C++
C
Output:
Enter two numbers: 
5 8
The greater number is 8 and the smaller number is 5

C++ Only Methods

  1. Returning multiple values Using References: We use references in C++ to store returned values. 
Output:
Enter two numbers: 
5 8
The greater number is 8 and the smaller number is 5
  1. Returning multiple values using Class and Object : The idea is similar to structures. We create a class with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. 
Output:
Enter two numbers: 
5 8
The greater number is 8 and the smaller number is 5
  1. Returning multiple values using STL tuple : The idea is similar to structures. We create a tuple with two integer variables and return the tuple, and then inside main function we use tie function to assign values to min and max that is returned by the function. 
Output:
The greater number is 8 and the smaller number is 5

Article Tags :

Similar Reads