YouTip LogoYouTip

Returning Values By Reference

# C++ Returning Values by Reference [![Image 3: C++ References](#) C++ References](#) Using references instead of pointers makes C++ programs easier to read and maintain. C++ functions can return a reference in a similar way to returning 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 ```cpp #include using namespace std; double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues(int i) { double& ref = vals; return ref; // Return a reference to the i-th element. ref is a reference variable, ref refers to vals } // 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 << endl; } setValues(1) = 20.23; // Change the 2nd element setValues(3) = 70.8; // Change the 4th element cout << "Values after change" << endl; for (int i = 0; i < 5; i++) { cout << "vals[" << i << "] = "; cout << vals << endl; } return 0; } When the above code is compiled and executed, it produces the following result: Values before change vals = 10.1 vals = 12.6 vals = 33.1 vals = 24.1 vals = 50 Values after change vals = 10.1 vals = 20.23 vals = 33.1 vals = 70.8 vals = 50 When returning a reference, be careful that the object being referred to does not go out of scope. So returning a reference to a local variable is not legal, but it is possible to return a reference to a
← C Function StrchrC Function Mbtowc β†’