Open In App

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

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
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++




// Modified program using pointers
#include <iostream>
using namespace std;
 
// add is the short name for address
void compare(int a, int b, int* add_great, int* add_small)
{
    if (a > b) {
 
        // a is stored in the address pointed
        // by the pointer variable *add_great
        *add_great = a;
        *add_small = b;
    }
    else {
        *add_great = b;
        *add_small = a;
    }
}
 
// Driver code
int main()
{
    int great, small, x, y;
 
    cout << "Enter two numbers: \n";
    cin >> x >> y;
 
    // The last two arguments are passed
    // by giving addresses of memory locations
    compare(x, y, &great, &small);
    cout << "\nThe greater number is " << great << " and the smaller number is "
      << small;
 
    return 0;
}
 
// This code is contributed by sarajadhav12052009


C




// Modified program using pointers
#include <stdio.h>
 
// add is the short name for address
void compare(int a, int b, int* add_great, int* add_small)
{
    if (a > b) {
 
        // a is stored in the address pointed
        // by the pointer variable *add_great
        *add_great = a;
        *add_small = b;
    }
    else {
        *add_great = b;
        *add_small = a;
    }
}
 
// Driver code
int main()
{
    int great, small, x, y;
 
    printf("Enter two numbers: \n");
    scanf("%d%d", &x, &y);
 
    // The last two arguments are passed
    // by giving addresses of memory locations
    compare(x, y, &great, &small);
    printf("\nThe greater number is %d and the smaller number is %d",
           great, small);
 
    return 0;
}


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. 

C




// Modified program using structures
#include <stdio.h>
struct greaterSmaller {
    int greater, smaller;
};
 
typedef struct greaterSmaller Struct;
 
Struct findGreaterSmaller(int a, int b)
{
    Struct s;
    if (a > b) {
        s.greater = a;
        s.smaller = b;
    }
    else {
        s.greater = b;
        s.smaller = a;
    }
 
    return s;
}
 
// Driver code
int main()
{
    int x, y;
    Struct result;
 
    printf("Enter two numbers: \n");
    scanf("%d%d", &x, &y);
 
    // The last two arguments are passed
    // by giving addresses of memory locations
    result = findGreaterSmaller(x, y);
    printf("\nThe greater number is %d and the"
           "smaller number is %d",
           result.greater, result.smaller);
 
    return 0;
}


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++




// Modified program using array
#include <iostream>
using namespace std;
 
// Store the greater element at 0th index
void findGreaterSmaller(int a, int b, int arr[])
{
 
    // Store the greater element at
    // 0th index of the array
    if (a > b) {
        arr[0] = a;
        arr[1] = b;
    }
    else {
        arr[0] = b;
        arr[1] = a;
    }
}
 
// Driver code
int main()
{
    int x, y;
    int arr[2];
 
    cout << "Enter two numbers: \n";
    cin >> x >> y;
 
    findGreaterSmaller(x, y, arr);
 
    cout << "\nThe greater number is " << arr[0]  << " and the "
           "smaller number is " << arr[1];
 
    return 0;
}
 
// This code is contributed by sarajadhav12052009


C




// Modified program using array
#include <stdio.h>
 
// Store the greater element at 0th index
void findGreaterSmaller(int a, int b, int arr[])
{
 
    // Store the greater element at
    // 0th index of the array
    if (a > b) {
        arr[0] = a;
        arr[1] = b;
    }
    else {
        arr[0] = b;
        arr[1] = a;
    }
}
 
// Driver code
int main()
{
    int x, y;
    int arr[2];
 
    printf("Enter two numbers: \n");
    scanf("%d%d", &x, &y);
 
    findGreaterSmaller(x, y, arr);
 
    printf("\nThe greater number is %d and the "
           "smaller number is %d",
           arr[0], arr[1]);
 
    return 0;
}


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. 

CPP




// Modified program using References in C++
#include <stdio.h>
 
void compare(int a, int b, int &add_great, int &add_small)
{
    if (a > b) {
        add_great = a;
        add_small = b;
    }
    else {
        add_great = b;
        add_small = a;
    }
}
 
// Driver code
int main()
{
    int great, small, x, y;
 
    printf("Enter two numbers: \n");
    scanf("%d%d", &x, &y);
 
    // The last two arguments are passed
    // by giving addresses of memory locations
    compare(x, y, great, small);
    printf("\nThe greater number is %d and the"
           "smaller number is %d",
           great, small);
 
    return 0;
}


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. 

CPP




// Modified program using class
#include <stdio.h>
 
class GreaterSmaller {
public:
    int greater, smaller;
};
 
GreaterSmaller findGreaterSmaller(int a, int b)
{
    GreaterSmaller s;
    if (a > b) {
        s.greater = a;
        s.smaller = b;
    }
    else {
        s.greater = b;
        s.smaller = a;
    }
 
    return s;
}
 
// Driver code
int main()
{
    int x, y;
    GreaterSmaller result;
 
    printf("Enter two numbers: \n");
    scanf("%d%d", &x, &y);
 
    // The last two arguments are passed
    // by giving addresses of memory locations
    result = findGreaterSmaller(x, y);
    printf("\nThe greater number is %d and the"
           "smaller number is %d",
           result.greater, result.smaller);
 
    return 0;
}


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. 

CPP




// Modified program using C++ STL tuple
#include<iostream>
#include<tuple>
 
using namespace std;
 
tuple <int, int> findGreaterSmaller(int a, int b)
{
    if (a < b) {
    return make_tuple(a, b);
    }
    else {
    return make_tuple(b, a);
    }
}
 
// Driver code
int main()
{
    int x = 5, y= 8;
    int max, min;
    tie(min, max) = findGreaterSmaller(x, y);
 
    printf("The greater number is %d and the "
        "smaller number is %d",
        max, min);
 
    return 0;
}
 
// This article is contributed by Blinkii


Output:

The greater number is 8 and the smaller number is 5


Similar Reads

How can I return multiple values from a function?
We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo
2 min read
C Function Arguments and Function Return Values
Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function
6 min read
Return values of printf() and scanf() in C/C++
What values do the printf() and scanf() functions return ? printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error Example 1: The printf() function in the code written below returns 6. As 'CODING' contains 6 characters. C/C++ Code // C/C++ program to demonstrate return value // of printf()
2 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
How to Pass or Return a Structure To or From a Function in C?
A structure is a user-defined data type in C. A structure collects several variables in one place. In a structure, each variable is called a member. The types of data contained in a structure can differ from those in an array (e.g., integer, float, character). Syntax: struct geeksforgeeks { char name[20]; int roll_no; char branch[20]; }[caption wid
3 min read
What is return type of getchar(), fgetc() and getc() ?
In C, return type of getchar(), fgetc() and getc() is int (not char). So it is recommended to assign the returned values of these functions to an integer type variable. char ch; /* May cause problems */ while ((ch = getchar()) != EOF) { putchar(ch); } Here is a version that uses integer to compare the value of getchar(). int in; while ((in = getcha
1 min read
Return Statement vs Exit() in main() in C++
The return statement in C++ is a keyword used to return the program control from the called function to the calling function. On the other hand, the exit() function in C is a standard library function of &lt;stdlib.h&gt; that is used to terminate the process explicitly. The operation of the two may look different but in the case of the main() funct
3 min read
What does main() return in C and C++?
C According to coding standards, a good return program must exit the main function with 0. Although we are using void main() in C, In which we have not suppose to write any kind of return statement but that doesn't mean that C code doesn't require 0 as exit code. Let's see one example to clear our thinking about need of return 0 statement in our co
3 min read
Return Statement in C
Pre-requisite: Functions in C C return statement ends the execution of a function and returns the control to the function from where it was called. The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc. In C, we can only return a single
4 min read
Difference between return and printf in C
In C programming, return and print serve fundamentally different purposes and they are used in distinct contexts to achieve specific tasks. Let's see each of them and see what are their functions and differences. 1. Return Statement In C, return is a statement used within a function to terminate the function's execution and return a value to the ca
2 min read
Article Tags :