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

In C or C++, we can’t return numerous qualities from a capacity straightforwardly. In this part, we will perceive how to utilize some stunts to return more than one worth from a capacity.

We can return more than one quality from a capacity by utilizing the technique called “call by address”, or “call by reference”. In the invoker work, we will utilize two factors to store the outcomes, and the capacity will take pointer type information. So we need to pass the location of the information.

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

In this model, we will perceive how to characterize a capacity that can return the remainder and leftover portion subsequent to partitioning two numbers from one single capacity.

Example Code

#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) {
   *quotient = a / b;
   *remainder = a % b;
}
main() {
   int a = 76, b = 10;
   int q, r;
   div(a, b, &q, &r);
   printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}

Output

Quotient is: 7
Remainder is: 6

New software engineers are typically in the inquiry of ways of returning numerous qualities from a capacity. Tragically, C and C++ don’t permit this straightforwardly. In any case, luckily, with a tad of astute programming, we can undoubtedly accomplish this.

The following are the strategies to return numerous qualities from a capacity in C:

Make a stride up from those “Hi World” programs. Figure out how to execute information structures like Heap, Stacks, Linked List, and some more! Look at our Data Structures in C course to begin adapting today.

  • By utilizing pointers.
  • By utilizing structures.
  • By utilizing Arrays.

Model: Consider a model where the undertaking is to view as the more noteworthy and more modest of two unmistakable numbers. We could compose numerous capacities. The principle issue is the difficulty of calling an overabundance to return numerous qualities and obviously, having more lines of code to be composed.

Returning numerous qualities Using pointers: Pass the contention with their location and make changes in their worth utilizing pointer. With the goal that the qualities get changed into the first contention.

  1. // 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
    
  2. 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.
    // 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
    
  3. 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].

    // 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.
    // 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
    
  2. 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.
    // 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
    
  3. 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.
    // 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

Also Read: Algorithm to solve Rubik’s Cube

Leave a Reply

Your email address will not be published. Required fields are marked *