Pointers for Call by Reference


//  this program swaps two integers
//  pointers are used for the parameters instead of reference vars

#include <iostream.h>

void swap(int*,int*);

int main()
{
   int num1 = 25;
   int num2 = 50;

//  print the original values
   cout << "num1 = " << num1 << endl;
   cout << "num2 = " << num2 << endl;
   cout << endl;

//  swap the values
   swap(&num1,&num2);

//  print the swapped values
   cout << "num1 = " << num1 << endl;
   cout << "num2 = " << num2 << endl;
   return 0;
}

//  swap: this function swaps the two parameters
void swap(int *ptr1, int *ptr2)
{
   int hold;

   hold = *ptr1;
   *ptr1 = *ptr2;
   *ptr2 = hold;
}

Output:

num1 = 25
num2 = 50
num1 = 50
num2 = 25

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2001