Return by Reference

A function can also return a reference. Consider the following function:
int & max (int &x, int &y)
{
if (x > y)
return x;
else
return y;
}

Since the return type of max() is int &, the function returns reference to x or y. Then a function call such as max (a,b) will yield a reference to either a or b depending on their values. This means that this function call can appear on the left hand side of an assignment statement. That is, the statement
max (a,b) = -1;
is legal and assigns -1 to a if it is larger, otherwise -1 to b.

No comments:

Post a Comment