C++ how to return a reference type variable in function
https:/w/ww.theitroad.com
In C++, you can also return a reference type variable from a function. To do so, you need to declare the function with the return type as a reference type.
Here's an example:
#include <iostream>
using namespace std;
int& max(int& x, int& y) {
if (x > y) {
return x;
} else {
return y;
}
}
int main() {
int a = 5, b = 3;
max(a, b) = 8; // Here, the value of 'a' will be updated to 8, as it's the larger variable.
cout << "a: " << a << ", b: " << b << endl; // Output: a: 8, b: 3
return 0;
}
In this example, the max() function returns a reference to an int. The function takes two int parameters and returns a reference to the larger one. In the main() function, the returned reference is assigned the value of 8, which is assigned to the a variable.
