Passing Address Constants Versus Passing Pointer Variables

Now that you know how the swap function works, we can elaborate on the two methods that PFUNC.C uses to pass the address of first and second to swap.

Summary: When you pass a pointer to a function, the function receives an address.

Earlier, we said the swap function expects to receive two pointers as parameters. While it's common to say pointers in this context, it would be more accurate to say the function expects addresses, since that's what it actually receives.

To work correctly, swap only needs the addresses of two variables. Once it has the addresses, it assigns them to its own local pointers and proceeds to do its work—modifying the original variables at long distance, as it were. The swap function doesn't care whether you pass the addresses as constants or pointer variables, since it receives the same kind of value in either case. The address is all the function needs to change the value of a variable defined elsewhere.

The first argument in the function call to swap shows a straightforward way to pass an address. Inside the main function of PFUNC.C, the expression &first equals the address of first. When you pass this argument to swap, the function clearly receives an address.

The second argument is an address, too. Since main assigns the address of second to the pointer variable ptr, the expression ptr equals the address of second. When you pass this argument to swap, the function also receives an address. (Remember, the value contained in a pointer variable is an address.)

Some beginning programmers get confused by functions that expect to receive pointers, thinking they must always pass pointer variables to such functions. As PFUNC.C shows, if the function expects an address you can simply pass the address as a constant, using the address-of operator.

NOTE:

When a function expects to receive an address as a parameter, you can pass either an address constant or a pointer variable, whichever is more suitable.

Why, then, would you ever go to the trouble of passing a pointer variable to this kind of function? In a real program, the function that calls swap might well use pointers to process first and second for some other purpose. In such a case you might prefer to use pointers in the function call, too.