Previous: 6.2.1 Indirectly Incrementing a Variable
Up: 6.2 Passing Pointers to Functions
Next: 6.2.3 A function to Swap Values
Previous Page: 6.2.1 Indirectly Incrementing a Variable
Next Page: 6.2.3 A function to Swap Values
Sometimes, whether a value should be returned as the value of a called function or indirectly stored in an object is a matter of choice. For example, consider a function which is required to ``return'' two values to the calling function. We know that only one value can be returned as the value of the function, so we can decide to write the function with one of the two values formally returned by a return statement, and the other value stored, by indirect access, in an object defined in the calling function. The two values are ``returned'' to the calling function, one formally and one by indirection.
Let us write a function to return the square and the cube of a value. We decide that the function returns the square as its value, and ``returns'' the cube by indirection. We need two parameters; one to pass the value to be squared and cubed to the function, and one pointer type parameter which will be used to indirectly access an appropriate object in the calling function to store the cube of the value. We assume all objects are of type double.
The code is shown in Figure 6.13. The prototype for sqcube() is defined to have two parameters, a double and a pointer to double, and it returns a double value. The printf() prints the value of x; the value of square which is the value returned by sqcube() (the square of x); and, the value of cube (the cube of x) which is indirectly stored by sqcube().
Figures 6.14 --- 6.17 show a step-by-step trace of the changes in objects, both in the calling function and in the called function. In the first step (Figure 6.14), the declarations for the function, and the template for the function, sqcube() are shown with the initialization of the variable, x, in main(). In the second step (Figure 6.15), the function, sqcube() is called from main() passing the value of x (3.0) to the first parameter, (called x in sqcube()), and the value of &cube, namely a pointer to cube, as the second argument to the parameter, pcube. In the third step (Figure 6.16), the first statement in sqcube() has been executed, computing the cube of the local variable, x, and storing the value indirectly in the cell pointed to by pcube. Finally, Figure 6.17 shows the situation just as sqcube() is returning, computing the square of x and returning the value which is assigned to the variable, square, by the assignment in .
While only one value can be returned as the value of a function, we loosely say that this function ``returns'' two values: the square and the cube of x. The distinction between a formally returned value and an indirectly or loosely ``returned'' value will be clear from the context.
Sample Session: