Call by Value

//  this program illustrates how call by value works. the value of a
//  formal parm is changed inside the function but the change is not
//  passed back to the caller because the parameter is passed by value

#include <iostream.h>

void sample(int);

int main()
{
   int num;

   num = 5;
   cout << "Before the call num = " << num << endl;
   sample(num);
   cout << "After the call num = " << num << endl;
   return 0;
}

//  sample changes the value of num and prints it
//  since num is passed by value the change is not returned to the caller
void sample(int num)
{
   num = 10;
   cout << "Inside the function num is changed to " << num << endl;
}

Sample Execution:

Before the call num = 5
Inside the function num is changed to 10
After the call num = 5


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

© Copyright Emmi Schatz 2002