next up previous
Next: Pointers Up: Functions Previous: Reference Parameters

Returning Reference

A function can return a reference. In C++ programming, there are several uses for reference return values.

Example

//Returning a reference
#include <iostream.h>
double &f();
double val=100.0;
main()
{
double newval;
cout <<f()<<'$\backslash$n';// Display val's value
newval =f(); //assign value of val to newval
cout <<newval<<'$\backslash$n'; // display newval's value
f()=99.5;//change val's value
cout <<f()<<'$\backslash$n';
return 0;
}
double &f()
{
return val;// return reference to val
}

The output of this program is shown here:

100
100
99.5

At the beginning, f() is declared as returning a reference to a double and the global variable val is initialized to 100. Next the following statement displays the original value of val:

cout <<f()<<'$\backslash$n';// Display val's value

When f() is called, it returns a reference to val. Because f() is declared as returning reference, the line

return val;

automatically returns a reference to val. This reference is then used by the cout statement to display val's value.

In the line

newval=f();

The reference to val is returned by f() is used to assign the value of val to newval.

The most interesting line in the program is shown here:

f()=99.5;

This statement causes the value of val to be changed to 99.5. Since f() returns a reference to val, this reference becomes the target of the assignment statement. Thus the value 99.5 is assigned to val indirectly through the reference to it returned by f().


next up previous
Next: Pointers Up: Functions Previous: Reference Parameters
Yousef Haik
2/23/1998