Program to swap two variables of any type


Generic approach can be used to swap two numbers of any data type. In this approach generic types are used as parameter in program, so they work for different data structures and data types. Template function swap(a,b) was used in this program, which creates different versions of swap() for interchanging  different data types like int, float and char.

Templates used are defined with a parameter which replaces the specified data type at the time of actual use of class or function. Below is the c++ program to swap two variables of any data type



using namespace std;

template <class T>
void swap(T &x, T &y)


T temp =x;


void interchange(int m,int n, float a, float b, char p, char q)
cout<<"m and n before swap :"<<m<<" "<<n<<endl;
cout<<"m and n after swap :"<<m<<" "<<n<<endl;

cout<<"a and b before swap :"<<a<<" "<<b<<endl;
cout<<"a and b after swap :"<<a<<" "<<b<<endl;

cout<<"p and q before swap :"<<p<<" "<<q<<endl;
cout<<"p and q after swap :"<<p<<" "<<q<<endl;

int main()

interchange (10,20,11.22,12.32,'a','b');
//return 0;	


Output :

m and n before swap :10 20
m and n after swap :20 10
a and b before swap :11.22 12.32
a and b after swap :12.32 11.22
p and q before swap :a b
p and q after swap :b a

In this program, functions were overloaded that can be used with different types of the data.

For example :

void interchange(int m,int n, float a, float b, char p, char q)


swap(m,n);// swap integers

swap(a,b); // swap float values

swap(p,q); // swap characters

To know the meaning of various keywords visit : c++ keywords-meanings

The following two tabs change content below.
Prashant Sharma

Latest posts by Prashant Sharma (see all)