This program works fine if I work with numbers but not with strings
Jan 16, 2019 at 7:31am UTC
If the variables are numbers I get the expected output
but if the variables are strings it bombs out.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include<iostream>
#include<string>
using namespace std;
template <class Type>
Type swapTwoVariables(Type& var1, Type& var2);
int main()
{
int var1; int var2;
cin >> var1 >> var2;
swapTwoVariables(var1, var2);
cout << var1 <<" " << var2;
//string var1;
//string var2;
//swapTwoVariables(var1, var2);
//cout << var1 << " " << var2;
}
template <class Type>
Type swapTwoVariables(Type& var1, Type& var2)
{
Type temp;
temp = var1;
var1 = var2;
var2 = temp;
}
It works fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include<iostream>
#include<string>
using namespace std;
template <class Type>
Type swapTwoVariables(Type& var1, Type& var2);
int main()
{
//int var1; int var2;
//cin >> var1 >> var2;
//swapTwoVariables(var1, var2);
//cout << var1 <<" " << var2;
string var1;
string var2;
swapTwoVariables(var1, var2);
cout << var1 << " " << var2;
}
template <class Type>
Type swapTwoVariables(Type& var1, Type& var2)
{
Type temp;
temp = var1;
var1 = var2;
var2 = temp;
}
It bombs out and I get a blank screen:
Process returned 255 (0xFF) execution time : 10.397 s
Press any key to continue.
please help
Jan 16, 2019 at 7:40am UTC
The program engenders undefined behaviour.
1 2 3 4 5 6 7 8 9 10 11 12
template <class Type>
Type swapTwoVariables(Type& var1, Type& var2)
{
Type temp;
temp = var1;
var1 = var2;
var2 = temp;
// *** warning: no return statement in function returning non-void (GNU)
// *** warning: control reaches end of non-void function (LLVM)
// *** error: 'swapTwoVariables<...>': must return a value (Microsoft)
}
http://coliru.stacked-crooked.com/a/480a0f09d4cc5246
https://rextester.com/CGDPB51654
Jan 16, 2019 at 9:09am UTC
Okay it now works fine.
I changed the template type to void and every thing now works fine
Thanks JLBorges
Topic archived. No new replies allowed.