An article and sample program covering the specific use of pass by reference in swapping integers using the C language; program swaps 2 integers from the command line.
Swapping is an important technique in solving many programming problems, and is often not well understood. The principle is simple enough: we want to assign the value of variable (a) to the value of variable (b) and vice versa. This is, however, an often complex 3-stage process:
Note that we talk of the 'value' of a variable - the contents of the variable - as opposed to the variable itself. This is important, as we shall see later on. The (temp) variable in the above 3-stage algorithm is just a holder for the value of variable (a), since (a) will be overwritten when it is assigned the value of variable (b).
Any kind of sorting algorithm will use swapping at some level, however the easiest to understand is the Bubble Sort mechanism. This is discussed further in Swapping Techniques in C Programming.
Having understood why swapping is important, and what it is supposed to achieve, we must now consider how it will be included in an application program. In order to be able to reuse the code, we will put it in a user-defined function. To do this we need to pass the variables to the function, let it do the swapping, and pass the variables back out again. By this logic, the variables need to be modifiable by the function.
In C programming this is the key difference between passing by reference and passing by value. If we pass the variables normally, they will be passed by value: a copy of the variable's assigned content will be passed to the function as a constant. This means that it can not be changed.
However, if we pass the variables by reference, then only a reference to the memory where the variable is stored is passed to the function. Using this reference, the function is able to modify the contents of the variable. Luckily, this is transparent to the programmer, as we only need to introduce the & operator like so:
The above is the first variant of a possible swapping function.
The code for the simplest 3-stage swapping function prototyped above looks like this:
This follows exactly the 3 stages in the Introduction.
We can use the function defined above in a simple program which takes 2 integers from the command line and returns them, swapped.
Only the main function is reproduced here, the C code file needs to also include the swapping function code itself. We also do not check for a valid argument list, in the interests of clarity. The atoi function is in the stdlib.h library, and the printf function is in the stdio.h library available with all C compiler kits.
More information about swapping techniques in C can be found at the following: