Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Pass By Reference

CS110 Lab: C++ Functions with Reference Parameters

A variable declared in the heading of a function is called a parameter, also called a formal argument or a formal parameter. A variable or expression included in the call to a function is referred to as an argument, also known as an actual argument or actual parameter. Please read the following for further information:

Reference Parameters

A reference parameter is declared by attaching an ampersand (&) to the name of its data type. It is called a reference parameter because the called function can refer to the corresponding argument directly. Specifically, the function is allowed to inspect and modify the caller's argument.

When a function is invoked using a reference parameter, it is the location (memory address) of the argument, not its value, that is passed to the function. There is only one copy of the information, and it is used by both the caller and the called function. In other words, the argument and the parameter refer to the same location in memory. If the value at that memory location is modified by the called function, then the caller will refer to that modified value as well.

Example


In the above example, the parameters firstValue and secondValue in the getData function are reference parameters. When getData is called in the main() function, the location of variables height and width are given to the getData() function. All references made to firstValue and secondValue inside the getData() function actually are made to height and width. The cin statement deposits values into the memory locations of the arguments height and width in the caller main().