Download this source file


// RefArgs.cpp - A program to demonstrate references and reference
// arguments in functions.
// Written by Wayne Pollock, Tampa Florida 2000

#include <iostream>

using namespace std;

void safe ( int num )               // Pass by copy is used here
{  cout << "In function \"safe\", arg \"num\" was " << num;
   ++num;
   cout << " and is now " << num << ".\n";
   return;
}


void dangerous ( int& num )        // Pass by reference is used here
{  cout << "In function \"dangerous\", arg \"num\" was " << num;
   ++num;
   cout << " and is now " << num << ".\n";
   return;
}


int main ()
{  int foo = 3;
   int& ref1 = foo;      // ref1 and foo are two names for the same variable.
   cout << "In main, foo = " << foo << " and ref1 = " << ref1 << ".\n";

   cout << "\nCalling function safe() now..." << endl;
   safe( foo );
   cout << "Back in main, foo = " << foo << " and ref1 = " << ref1 << ".\n";

   cout << "\nCalling function dangerous() now..." << endl;
   dangerous( foo );
   cout << "Back in main, foo = " << foo << " and ref1 = " << ref1 << ".\n";

   return 0;
}



#ifdef COMMENTED_OUT           // Output of above program:

In main, foo = 3 and ref1 = 3.

Calling function safe() now...
In function "safe", arg "num" was 3 and is now 4.
Back in main, foo = 3 and ref1 = 3.

Calling function dangerous() now...
In function "dangerous", arg "num" was 3 and is now 4.
Back in main, foo = 4 and ref1 = 4.

#endif