Returning More Values By Reference
The return() statement has one big limitation that it can return only one value at a time. The return() statement is only used when values are passed by value to functions. Call by address and call by reference, accesses memory location directly. When user wants to return more than one value from function, he/she should pass values by address or by reference method. In C for returning more values, call by address is used. In C++ we have one additional method, that is call by reference. Consider the following program.
7.9 Write a program to return more than one value from function by reference.
Explanation: In the above program the function more() is used to perform square and cube of an integer passed. The three variables sq, cb, and n of integer type are declared. The number entered by the user is stored in variable n. The variables sq, cb, and n are passed to function more().
In function more(), s and j are reference variables and j is a local variable of function more(). The variable s is reference variable of sq and variable c is reference variable of cb. The variables s and sq, and c and cb have the same memory locations. Thus, any value assigned to s and c can be accessed by sq and cb. The variable s is assigned the square of j(n) and variable cb is assigned with cube of j(n).