PASS BY REFERENCE

Examine The file named PASSREF.CPP for an example of a pass by reference, a construct which is not available in ANSI-C.

The reference variable was mentioned in chapter 1 and it was recommended there that you don’t use it in the manner illustrated there. This example program illustrates a situation where it can be used to your advantage. The pass by reference allows the passing of a variable to a function and returning the changes made in the function to the main program. In ANSI-C the same effect can be seen when a pointer to a variable is passed to a function, but use of a reference variable is a little cleaner.

Observe the prototype in line 4 where the second variable has an ampersand in front of the variable name. The ampersand instructs the compiler to treat this variable just like it were passed a pointer to the variable since the actual variable from the main program will be used in the function. In the function itself, in lines 21 through 24, the variable in2 is used just like any other variable but we are using the variable passed to this function from the main program not a copy of it. The other variable named in1 is treated just like any other normal variable in ANSI-C. In effect, the name in2 is a synonym for the variable named index in the main program.

If you prefer to omit the variable names in the prototypes, you would write the prototype as follows;

void fiddle(int, int&);

If you are a Pascal programmer, you will recognize that the variable named in1 is treated just like a normal parameter in a Pascal call, a call by value. The variable named in2 however, is treated like a variable with the reserved word VAR used in front of it usually referred to as a call by reference. The reference variable is actually a self dereferencing pointer which refers to, or points to, the original value.

When you compile and execute this program, you will find that the first variable got changed in the function but was returned to its original value when we returned to the main program. The second variable however, was changed in the function and the new value was reflected back into the variable in the main program which we can see when the values are listed on the monitor.