Skip to main content

Section 10.2 References and Functions

We normally don’t use references like was shown in the previous section. Having two names for the same local variable does nothing but cause confusion. Instead, references are used to allow us to share an existing storage location with a new scope instead of making a copy of what is stored.
For example, normally when we pass something to a function, a copy is made of the passed value. The copy is stored into the parameter. Take this example:
Listing 10.2.1.
This is called pass by value because the parameter x in add gets a copy of the value of number from main. The memory diagram when we reach line 6 (after calling add from main) would look like:
Figure 10.2.2. Memory diagram for add and main
x simply holds a copy of the number from main. No matter what we do to x inside add, we can’t change what number holds. However, if we make x a reference, the memory diagram will look like:
Figure 10.2.3. Memory diagram for add and main where s is a reference.
Now x is a reference to number. This is called pass by reference. It links back to the memory in the main stack frame. If we change x, we change number. Try it out in this sample. The only change we have made is to make chop take a reference to an int: add(int& x).
Listing 10.2.4.

Checkpoint 10.2.1.

You have attempted of activities on this page.