Call by Value and Call by Reference in C++
Call by Value and Call by Reference in C++
Let's understand call by value and call by reference in C++ language one by one.
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:
By Mahesh Patidar
Call By Value and Call By Reference Concept and program
#include <iostream.h>
#include<conio.h>
Void main()
{
Dat= 3
Clrscr(); // call library function
int dat = 3;
cout << "Value of the data in main function is: " << dat<< endl;
change(dat); // Calling of function
}
void change(int data) // definition of function
{ 3
Output:
#include <iostream.h>
Void main()
{
int a=3; // Memory address = 10000AB
int *b; // pointer variable Memory address = 20000AB
b = & a; //address of b=10000AB
cout << "Value of a is: " << a; //3
cout<<”Address of a is:”<<&a; // 10000AB
cout<<”Address of a is:”<< b; // 10000AB
*b=100+5;
cout<<”Value at given Address stored in b:”<<* b; //105
*b=10;
By Mahesh Patidar
Call By Value and Call By Reference Concept and program
A 10000AB B 20000AB
105 10000AB
By Mahesh Patidar
Call By Value and Call By Reference Concept and program
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>
Void main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
Output:
By Mahesh Patidar
Call By Value and Call By Reference Concept and program
2 Changes made inside the function is Changes made inside the function is
not reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
By Mahesh Patidar