call by value vs call by reference cpp swapping example

Swapping Call by value example :-
#include<iostream.h>
#include<conio.h>
void swap(int x, int y){
int z;
z=x;
x=y;
y=z;
cout<<"After Swapping a="<<x<<" b="<<y<<endl;
}
void main(){
int a,b;
clrscr();
cout<<"enter two numbers"<<endl;
cin>>a>>b;
cout<<"Before Swapping a="<<a<<" b="<<b<<endl;
//Call by value
swap(a,b);
getch();
}
Swapping Call by reference example :-
#include<iostream.h>
#include<conio.h>
void swap(int *x, int *y){
int z;
z=*x;
*x=*y;
*y=z;
}
void main(){
int a,b;
clrscr();
cout<<"enter two numbers"<<endl;
cin>>a>>b;
cout<<"Before Swapping a="<<a<<" b="<<b<<endl;
//Call by reference
swap(&a,&b);
cout<<"After Swapping a="<<a<<" b="<<b<<endl;
getch();
}

No comments:

Post a Comment