hello, i have this code and i dont know why it does not run .
the question is write the definition of the function template which exchanges two variables by taking the two variables as parameters and swaps them.
this is my try.
#include <iostream>
usingnamespace std;
template<typename T>
T swapp(T &num1, T &num2) {
T temp=num1;
num1=num2;
num2=temp;
return temp;
}
int main()
{
int a =8;
int b =4;
cout<<swapp(a,b);
cout<<endl;
double x = 2.3;
double y = 4.5;
cout<<swapp(x,y);
system("pause");
return 0;
}
Why does the "swapp" function return a value? When you call the function in the cout statement, you're going to print the return value and not the actual parameters. Try this in main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int a = 8;
int b = 4;
cout<<"a = " << a << endl;
cout<<"b = " << b <<endl;
cout<<"Calling swap"<<endl;
swapp(a,b);
cout<<"a = " << a << endl;
cout<<"b = " << b <<endl;
double x = 2.3;
double y = 4.5;
cout<<"x = " << x << endl;
cout<<"y = " << y <<endl;
cout<<"Calling swap"<<endl;
swapp(x,y);
cout<<"x = " << x << endl;
cout<<"y = " << y <<endl;