C++ Swapping

Swapping variables is a most common stuff among the programmers and there are various methods to do that.In C++ and C there is especial way to do swapping.Using pointers we can swap variables. Here I listed two ways to do the swapping by using Pass by Reference method.

#include <iostream>

using namespace std;

//Normal swap without a temp variable
void swap(int& x,int& y){

x=x+y;
y=x-y;
x=x-y;
}
//Pointer swap using a temp variable
void pswap(int& x,int& y){

int* p1;
int* p2;
int temp;

p1=&x;
p2=&y;

temp=*p1;
*p1=*p2;
*p2=temp;
}

int main(){

int q1=3;
int q2=4;

int q3=5;
int q4=6;

swap(q1,q2);
pswap(q3,q4);

cout<<"Normal Swap: "<<q1<<" and "<<q2<<endl;
cout<<"Pointer Swap: "<<q3<<" and "<<q4<<endl;

return 0;
}

If you are a Linux user, this is the command to compile your source code using Linux Terminal(Suppose you saved above source code with name “ex1.cpp”)

 
g++ ex1.cpp -o ex1.out

It creates machine executable object called “ex1.out”. Then you can run above compiled code by executing the following command.(You can give a different name for .out file)

./ex1.out

Hope this little thing helped you !