Return to examples
Pass-By-Reference with alias:
The following example is on page 356.
Formal parameter, a, uses the same box as actual parameter, i.
i is a global variable. So, when b copy to i, the a is changed.
#include <iostream.h>

int i = 3;   /* i is a global variable */

void fun(int &a, int &b)
{

  cout<<"Beginning of subprogram:"<<endl;
  cout<<"a = " <<a<<endl;
  cout<<"b = " <<b<<endl;
  cout<<"i = " <<i<<endl;
  i = b;
  cout<<"Ending of subprogram:"<<endl;
  cout<<"a = " <<a<<endl;
  cout<<"b = " <<b<<endl;
  cout<<"i = " <<i<<endl;
}

void main()
{
  int list[5]={2, 0, 4, 5, 3};

  cout<<"Before call: \n";
  cout<<"i = " <<i<<endl;
  cout<<"list[i] = " <<list[i]<<endl;
  for(int j=0; j<5; j++)
    cout<<list[j]<<" ";
  cout<<endl;
  fun (i, list[i]);
  cout<<"After call: \n";
  cout<<"i = " <<i<<endl;
  cout<<"list[i] = " <<list[i]<<endl;
  for(int k=0; k<5; k++)
    cout<<list[k]<<" ";
  cout<<endl;
}
The output will be
Before call:
i = 3
list[i] = 5
2 0 4 5 3
Beginning of subprogram:
a = 3
b = 5
i = 3
Ending of subprogram:
a = 5
b = 5
i = 5
After call:
i = 5
list[i] = 0  (for VAX, it is 0, however, for Microsoft C++, it is a garbage.)
2 0 4 5 3