Returning References as Return Values in C++
Using references instead of pointers can make C++ programs easier to read and maintain. C++ functions can return a reference, similar to how they return a pointer.
When a function returns a reference, it returns an implicit pointer to the return value. This allows the function to be placed on the left side of an assignment statement. For example, consider the following simple program:
Example
#include <iostream>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues(int i) {
double& ref = vals[i];
return ref; // Returns a reference to the i-th element, ref is a reference variable, ref refers to vals[i]
}
// Main function to call the above defined function
int main ()
{
cout << "Values before change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
setValues(1) = 20.23; // Changes the 2nd element
setValues(3) = 70.8; // Changes the 4th element
cout << "Values after change" << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Values before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
Values after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50
When returning a reference, be aware that the referenced object must not go out of scope. Therefore, returning a reference to a local variable is illegal. However, you can return a reference to a static variable.
int& func() {
int q;
//! return q; // Error at compile time
static int x;
return x; // Safe, x remains valid outside the function scope
}