Reputation: 4297
swap(string1,string2) will swap two strings values easily while I use it in Main Function, But if I use it in another function and call it from main function it won't work!
this works:
int main()
{
string name1="A",name2="B";
swap(name1,name2);
}
but this one does not:
string name1="A",name2="B"; // Global Here
void exchange (string one,string two)
{
swap(one,two);
}
int main()
{
exchange(name1,name2);
}
where is the problem?
Upvotes: 1
Views: 538
Reputation: 76
Pass the strings by reference instead of by value, otherwise exchange
will modify local copies of one
and two
.
string name1="A", name2="B"; // Global Here
void exchange(string& one, string& two)
{
swap(one,two);
}
int main()
{
cout << name1 << "\n" << name2 << endl;
exchange(name1, name2);
cout << name1 << "\n" << name2 << endl;
}
Output:
A
B
B
A
Upvotes: 6
Reputation:
void exchange (string& one,string& two)
{
swap(one,two);
}
This should work. The amperstand (&) means that you are passing the arguments by reference, and that the function is allowed to modify the initial strings that were passed as parameters. If you do not use &, the strings will be passed by value and you will only modify copies of the actual strings.
Upvotes: 2
Reputation: 153840
Well, the values of the copies one
and two
actually are swapped. It won't affect the variables name1
and name2
, of course. Assuming you want the values of these strings being swapped, you should pass the arguments by reference
void exchange(string& one, string& two) {
...
}
Upvotes: 2