Call by Value and Call by Reference in c++

call by value and call by reference in c++

Call By Value in C++

understanding call by value and call by reference in c++

when you call function and give function argument, argument will pass as value it is called call by value method.

when you call a function, the actual argument value is copied in function parameters. and will use new space in computer memory. when you change in function then the original data does not change. only copied data will be changed.

if You want to use changed data, you must use the return function to get changed  formal data else you can use changed data only those function

Example of Call by Value

#include<iostream>
using namespace std;

void exchange(int a, int b)
{
   int temp;
   temp = a;
   a = b;
   b = temp;
   cout<<"x = " << a << endl;
   cout<<"y = " << b << endl;
}

int main(){
   int x=10;
   int y=25;
   cout<<"x = " << x << endl;
   cout<<"y = " << y << endl;
   cout<<""After Exchange<< endl;
   exchange(x,y);
}

output

x = 10
y = 25
After Exchange
x = 25
y = 10

call using Reference

when you call a function and pass a function’s actual arguments Address in a function definition, then argument data will pass as an address it is called the call by Reference method.

When you call the function and pass the Address of the variables which you want to use in your function.

so the function will store the address and the program will access the value directly by getting the value on the passed address in the function.

You will change to data so data will be changed permanently Because actual values do not copy in dummy variable

this concept uses multiple programming languages so you should have to understand the concept

Example of call By Reference in c++

#include<iostream>
using namespace std;

void exchange(int *a, int *b)
{
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
}

int main(){
   int x=10;
   int y=25;
   cout<<"x = " << x << endl;
   cout<<"y = " << y << endl;
   cout<<""After Exchange<< endl;
   exchange(x,y);
   cout<<"x = " << x << endl;
   cout<<"y = " << y << endl;
}

Output

x = 10
y = 25
After Exchange
x = 25
y = 10