Home Uncategorized Write a program to implement call by value and call by reference...

Write a program to implement call by value and call by reference using reference variable

SHARE

AIM: Write a C++ program to implement call by value and call by reference.

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let’s try to understand the concept of call by value in C++ language by the example given below:

#include <iostream>
using namespace std;
void change(int data);
int main()
{
   int data;
   cout<<”Enter a value : “;
   cin>>data;
   cout << “Given number is: ” << data<< endl;
   change(data);
   cout << “In main function original Value is unchanged: ” << data<< endl;
   return 0;
}
void change(int data)
{
   data = data + 5;
   cout<<”In calling function given value is changed as : “<<data<<endl;
}

Output:

Enter a value: 965
Given number is: 965
In calling function given value is changed as: 970
In main function original Value is unchanged: 965

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let’s try to understand the concept of call by reference in C++ language by the example given below:

#include <iostream>
using namespace std;
void change(int *data);
int main()
{
   int data;
   cout<<”Enter a value : “;
   cin>>data;
   cout << “Given number is: ” << data<< endl;
   change(&data);
   cout << “In main function original Value is changed: ” << data<< endl;
   return 0;
}

void change(int *data)
{
   *data = *data + 5;
   cout<<”In calling function given value is changed as : “<<data<<endl;
}

Output:

Enter a value: 1968
Given number is: 1968
In calling function given value is changed as: 1973
In main function original Value is changed: 1973

Difference between call by value and call by reference in C++

No. Call by value Call by reference
1 A copy of value is passed to the function. An address of the value is passed to the function.
2 Changes made inside the function is not reflected on other functions. Changes made inside the function is reflected outside the function also.
3 Actual and formal arguments will be created in different memory location. Actual and formal arguments will be created in same memory location.

Back to Programs.