Functions with pass by reference

One place where it is useful to use pass by reference is when we need to swap, or exchange the values of two variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Pass by refernece
#include<iostream>
using namespace std;
void exchange(double&,double&);
int main()
{ double num1, num2;
  cout<<"Enter the first number:";
  cin>>num1;
  cout<<"Enter the second number:";
  cin>>num2;
  if(num1>num2) exchange(num1,num2);
  cout<<"The numbers are "<<num1<<" and "<<num2<<endl;
  system("pause");
  return 0;
} //main
void exchange(double &a,double &b) {
  double temp=a;
  a=b;
  b=temp;
}
CODE

In the illustration, the variables in main are at memory locations 0x0019F9B8 and 0x0019F9A8. In the function exchange, the same two locations are used to exchange the values. This will only work if you use pass by reference.
memory

NEXT: Arrays