Sunday 23 November 2014

Difference between call by value and call by reference

1. In call by value we pass a copy of actual arguments to formal arguments however in call by reference we pass the original values through reference variable.
2.In call by value if we make any change in formal argument the same changes will not take place in actual argument, whereas in call by reference the changes will take place in call by reference.

Example of call by value

#include<iostream.h>
#include<conio.h>
void swap(int,int);
void main()
{
clrscr();
int x,y;
cout<<"enter two numbers "<<endl;
cin>>x>>y;
swap(x,y);  // actual arguments
cout<<"After Swapping:-"<<endl;
cout<<"The value of x is "<<x<<endl;
cout<<"The value of y is "<<y<<endl;
getch();
}
void swap(int a,int b)        // Formal arguments
{
int c;
c=a;
a=b;
b=c;
cout<<"In swap function :-"<<endl;
cout<<"The value of a is "<<a<<endl;
cout<<"The value of b is "<<b<<endl;
}

Output :
Enter two number 
10
20

In Swap function:-
The value of a is 20
The value of b is 10
In main function:-
The value of x is 10
The value of y is 20

Example of call by reference

#include<iostream.h>
#include<conio.h>
void swap(int & ,int &);
void main()
{
clrscr();
int x,y;
cout<<"enter two numbers "<<endl;
cin>>x>>y;
swap(x,y);  // actual arguments
cout<<"After Swapping:-"<<endl;
cout<<"The value of x is "<<x<<endl;
cout<<"The value of y is "<<y<<endl;
getch();
}
void swap(int &a,int &b)        // Formal arguments
{
int c;
c=a;
a=b;
b=c;
cout<<"in swap function :-"<<endl;
cout<<"The value of a is "<<a<<endl;
cout<<"The value of b is "<<b<<endl;
}


Output :
Enter two number 
10
20

In Swap function:-
The value of a is 20
The value of b is 10
In main function:-
The value of x is 20
The value of y is 10