swap using reference

Passing by reference makes the local variable a reference to the argument. Local variable are the copy of the arguments passed by reference.

So, any change made to the local variable is reflected in the argument passed. Argument is passed by reference using & sign.

#include<iostream>
using namespace std;
void swap(int& x,int& y){
	int temp;
	temp = x;
	x = y;
	y = temp;
}
int main(){
	int a = 10;
	int b = 35;
	cout<<"a = "<<a<<" b = "<<b<<endl;
	swap(a,b);
	cout<<"After swapping"<<endl;
	cout<<"a = "<<a<<" b = "<<b<<endl;
	return 0;
}
output of the above program. swapping using reference
output of the above program. swapping using reference

Leave a Reply