Besides passing parameters to a function, references can also be used to return values from a function. For example:
int mynum = 0; // Global variable
int &num()
{
return mynum;
}
void main()
{
int i;
i = num();
num() = 5; // mynum set to 5
}
In this example, the return value of the function num is a reference initialized with the global variable mynum. As a result, the expression num() acts as an alias for mynum. This means that a function call can appear on the receiving end of an assignment statement, as in the last line of the example.
You'll learn some more practical applications of this technique in Chapter 5, “Classes and Dynamic Memory Allocation,” and Chapter 8, “Operator Overloading and Conversion Functions.”
Passing a reference to a function and returning a reference from a function are the only two operations that you should perform on references themselves. Perform other operations on the object it refers to.