Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Return multiple values from a function in C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

There may be times while solving a problem that you need to return multiple values (maybe of different data types). Unfortunately, it is impossible to return multiple values in C and C++ directly. However, we can easily accomplish this with a bit of smart programming. In this blog, we will learn about different methods of returning multiple values from a function in C++.

Below are the four methods to return multiple values from a C++ function:

  • By using pointers
  • By using structs
  • By using arrays
  • By using tuples/pairs
     

Also see, Literals in C, Fibonacci Series in C++

By using pointers

We can pass the desired variables as pointers(i.e., with their addresses) and then make changes in these variables using pointers so that the value of the original variables gets changed.

Program

// Modified program using pointers
#include <bits/stdc++.h>

using namespace std;

// add is the short name for address
void compare(int a, int b, int* ptr_greater, int* ptr_smaller){
    if (a > b) {
        // a is stored in the address pointed
        // by the pointer variable *ptr_greater
        *ptr_greater = a;
        *ptr_smaller = b;
    }
    else {
        *ptr_greater = b;
        *ptr_smaller = a;
    }
}

// Driver code
int main(){
    int greater, smaller, x, y;

    x = 10;
    y = 20;

    // The last two arguments are passed
    // by giving addresses of memory locations
    compare(x, y, &greater, &smaller);

    cout << "Greater element: " << greater << endl;
    cout << "Smaller element: " << smaller << endl;
    return 0;
}

Output

Greater element: 20
Smaller element: 10
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

By using structs

Structs are defined by the user, and they can contain different & multiple fields. So we can use these structs to return multiple values (maybe of various types) from a function.

Program

// Modified program using structures
#include <bits/stdc++.h>

using namespace std;


struct answer {
    int greater, smaller;
};

typedef struct answer answer;

answer compare(int a, int b){
    answer 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;
    answer result;

    x = 10;
    y = 20;

    // The last two arguments are passed
    // by giving addresses of memory locations
    result = compare(x, y);
   
    cout << "Greater element: " << result.greater << endl;
    cout << "Smaller element: " << result.smaller << endl;
    return 0;
}

Output

Greater element: 20
Smaller element: 10

 

You can try by yourself with the help of online c++ compiler.

By using arrays

This method only works when the items to be returned are of the same data type. When an array is passed as an argument to a function in C++, its base address (pointer/address to starting element) gets passed into the function. So whatever changes are made to the argument array in the function are also reflected in the original array. Therefore we can use an array to return similar kinds of values.

Program

// Modified program using array
#include <bits/stdc++.h>

using namespace std;

// Store the greater element at 0th index
void compare(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];

    x = 10;
    y = 20;

    compare(x, y, arr);

    cout << "Greater element: " << arr[0] << endl;
    cout << "Smaller element: " << arr[1] << endl;
    return 0;
}

Output

Greater element: 20
Smaller element: 10

By using tuples/pairs

We can also declare the function with a return type as a tuple or pair (according to the desired types of values that need to be returned). We can then pack the values to be returned, and on the calling side, we can unpack these values accordingly.

Program

// Modified program using pairs & tuple
#include<bits/stdc++.h>

using namespace std;

// A Method that returns multiple values using
// tuple in C++.
tuple<int, int, char> funcTuple(int n1, int n2){
    // Packing values to return a tuple
    return make_tuple(n2, n1, 'c');        
}

// A Method returns a pair of values using pair
pair<int, int> funcPair(int a, int b){
    // Packing two values to return a pair
    return make_pair(b, a);        
}

int main(){
    int n1,n2;
    char character;
   
    // Unpack the elements returned by funcTuple
    tie(n1, n2, character) = funcTuple(99, 88);
   
    // Storing returned values in a pair
    pair<int, int> p = funcPair(66, 22);
   
    cout << "Values returned by tuple: ";
    cout << n1 << " " << n2 << " " << character << endl;
   
    cout << "Values returned by Pair: ";
    cout << p.first << " " << p.second;
    return 0;
}

Output

Values returned by tuple: 88 99 c
Values returned by Pair: 22 66

Check out this problem - Next Smaller Element

FAQs

1. What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm in which the entire software is composed of a collection of objects that communicate with one another. A collection of data and methods that operate on that data is referred to as an object.

2. What are the main features of OOPs?
Following are the main features of OOPs:
a) Polymorphism
b) Inheritance
c) Encapsulation
d) Abstraction

3. What is Inheritance?
The concept of inheritance is simple: a class is built on another class and uses the other class's data and implementation. The goal of inheritance is to reuse code.

4. What is a Namespace?
All C++ programmes must include Namespaces. In C++, namespaces define a scope for the identifiers used in the programme.

5. What are cin and cout in C++?
The object of the ostream class is cout. By default, the cout stream is connected to the console output device. Its main purpose is to display characters on the console screen. It's analogous to the printf function in C. The object of the istream class is cin. By default, the cin stream is connected to the console input device. Its main purpose is to extract characters from the user. In C, it's similar to scanf.

Key Takeaways

Cheers if you reached here!! 

In this article, we learned about different methods of returning multiple values from a function in C++. We also saw an example implementation of each method.

Recommended Readings:


We hope that this blog has helped you enhance your knowledge regarding returning values from functions in C++ and if you would like to learn more, check out our articles on the platform Coding Ninjas Studio. Also, do check out our course on C++. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
By using pointers
2.1.
Program
2.2.
Output
3.
By using structs
3.1.
Program
3.2.
Output
4.
By using arrays
4.1.
Program
4.2.
Output
5.
By using tuples/pairs
5.1.
Program
5.2.
Output
6.
FAQs
7.
Key Takeaways