Return multiple values from a function in C++
In this tutorial, we will learn how to return multiple values from a function in C++.
In C++, we cannot directly return the multiple values from a function. But, instead, we will be using different tricks for returning multiple values from a function.
So, we can return multiple values from a function via Call by Address or Call by Reference.
Call By Address to return multiple values from a function
The sample code is as follows…
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void func(int x,int y,int *c,int *d)
{
*c=x+y;
*d=x-y;
}
int main()
{
int x,y;
cout<<"Enter the values of x and y\n";
cin>>x>>y;
int c,d;
func(x,y,&c,&d);
cout<<"The value of c is : "<<c<<" \nThe value of d is : "<<d;
return 0;
}Output :
Enter the values of x and y 10 5 The value of c is : 15 The value of d is : 5
Explanation :
- Here we need to take the input from the user(i.e… x and y values).
- Then we must pass the parameters x and y values with c and d by call by address.
- Then the operations which need to be done on c and d are performed.
- At last, by cout statement, the multiple values are returned.
Call By Reference
The Sample code is as follows…
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void func(int x,int y,int &c,int &d)
{
c=x+y;
d=x-y;
}
int main()
{
int x,y;
cout<<"Enter the values of x and y\n";
cin>>x>>y;
int c,d;
func(x,y,c,d);
cout<<"The value of c is : "<<c<<" \nThe value of d is : "<<d;
return 0;
}
Output :
Enter the values of x and y 10 5 The value of c is : 15 The value of d is : 5
Explanation :
- Even here first the x and y values were read from the user.
- Then that x and y values along with c and d are passed as the parameters by call by reference.
- Then c and d get its value by addition and subtraction.
- Then at last the multiple values are returned by using cout.
Leave a Reply