C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Functions  >  Call by Reference
 

Call by Reference

A reference provides an alias- an alternate name- for the variable. While passing reference arguments, a reference to the variable in the calling program is passed.

Program 7.4 can be modified using reference arguments in the following way:

//Program 7.6
//This program swaps the values in the variable using function containing reference arguments
#include<iostream.h>
void swap(int &iNum1, int &iNum2);
void main()
{
int iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}

void swap(int &iNum1, int &iNum2)
{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}


Reference arguments are indicated by an ampersand (&) preceding the argument:

int &iNUm1;

In Program 7.6, the ampersand (&) indicates that iNum1 is an alias for iVar1 which is passed as an argument.

The function declaration must have an ampersand following the data type of the argument:

void swap(int &iNum1, int &iNum2)

The ampersand sign is not used during the function call:

swap(iVar1, iVar2);

The sample output of Program 7.6 is:

Enter two numbers
12
24
In swap 24 12
In main 24 12

In Program 7.6, the values in the variables iVar1 and iVar2 in the calling program are swapped.

This is depicted in Figure 7.3

 

iVar1   iVar2

24

 

12

iNum1   iNum2
     
Figure 7.3 After Swap() Function is Executed
 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.