What is the difference between call by value and call by reference in c++?

Image result for call by value and call by reference

1 -
Call by value -

In call by value function, when you make variables and pass them in function, it passes only the value stored in it and it stores that value within other variable during function run. So, your initial value of variables remains same because function uses different variables for it’s work and stores your initial variables value in different variable.
#include <iostream>
#include <stdlib.h>
using namespace std;

void swap( int, int );

int main(){
 system("cls");
 int x, y;
 cout<<"Enter two numbers\n";
 cin>>x>>y; //use spacebar after entering first number
 cout<<"Numbers before swapping are "<<x<<" and "<<y;
 swap(x,y);
cout<<"\nNumbers after calling swap function are "<<x<<" and "<<y
;}

void swap( int a, int b ){
 int temp;
 temp=a;
 a=b;
 b=temp;
}
Let inputs be 5 and 7 .
In the above example output will be -
Numbers before swapping are 5 and 7
Numbers after swapping are 5 and 7
You can see that value of numbers before and after swapping remains same.


2 - Call by reference -

In call by reference function, when you make variables and pass them in function, it passes the address stored in it( i.e ).So, variables made within function will store the address of variables passed but not the value(i.e they will act as a pointer). So, when you change the value of variables within function then it will refer to actual variable and change the value of actual variable.
#include <iostream>
#include <stdlib.h>
using namespace std;

void swap( int &, int & );

int main(){
 system("cls");
 int x, y;
 cout<<"Enter two numbers\n";
 cin>>x>>y; //use spacebar after entering first number
 cout<<"Numbers before swapping are "<<x<<" and "<<y;
 swap(x,y);
cout<<"\nNumbers after calling swap function are "<<x<<" and "<<y
;}

void swap( int &a, int &b ){
 int temp;
 temp=a;
 a=b;
 b=temp;
}
Let inputs be 5 and 7 .
In the above example output will be -
Numbers before swapping are 5 and 7
Numbers after swapping are 7 and 5
You can see that value of numbers before and after swapping are changed.

Feel free to ask any doubt.

Post a Comment

0 Comments