Returning multiple values from a C++ function

In C or C++, we cannot return multiple values from a function directly. In this section we will see how to use some trick to return more than one value from a function.

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

In this example we will see how to define a function that can return quotient and remainder after dividing two numbers from one single function.

Example

#include<iostream>
using namespace std;
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);
cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}

Output

Quotient is: 7
Remainder is: 6

Call By Reference

Example

#include<iostream>
using namespace std;
void div(int a, int b, int "ient, int &remainder) {
quotient = a / b;
remainder = a % b;
}
main() {
int a = 76, b = 10;
int q, r;
div(a, b, q, r);
cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}

Output

Quotient is: 7
Remainder is: 6