Previous: 6.2.2 Computing the Square and Cube
Up: 6.2 Passing Pointers to Functions
Previous Page: 6.2.2 Computing the Square and Cube
Next Page: 6.3 Returning to the Payroll Task with Pointers
We have already seen how values of two objects can be swapped directly in the code in main(). We now write a function, swap(), that swaps values of two objects defined in main() (or any other function) by accessing them indirectly, i.e. through pointers. The function main() calls the function, swap(), passing pointers to the two variables. The code is shown in Figure 6.18. (We assume integer type objects in main()).
The function, swap(), has two formal parameters, integer pointers, ptr1 and ptr2. A temporary variable is needed in the function body to save the value of one of the objects. The objects are accessed indirectly and swapped. Figures 6.19 --- 6.22 show the process of function call, passed values, and steps in the swap.
Sample Session: