CS110 Lab: C++ Function 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

// Program DemoRef prompts for and reads two integer
// values that represent the sides of a rectangle.    
// The area of the rectangle is calculated and printed.

#include <iostream>
using namespace std;

void GetData(int&, int&);	// function prototype
// GetData gets two integer values.

int main()
{
    int  height;
    int  width;
    int  area;

    GetData(height, width);		//function call
    area = height * width;


    cout << "The area of the "  << height  << " by "
         << width  << " rectangle is "  << area  << endl;
    return 0;
}

//************************************************************************
//Function definition with two reference parameters
//************************************************************************

void GetData(int& firstValue, int& secondValue) 
// Post: The user has been prompted to input two values        
//       representing the length and width of a rectangle. 
//       These values have been read and returned in 
//       firstValue and secondValue.   
{   
    cout  << "Enter two integer values representing "
          << "a rectangle.  Press return."  << endl;
    cin  >> firstValue  >> secondValue;
}

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.


Copyright: Department of Computer Science, University of Regina.