1

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?

Nate Kohl
  • 35,264
  • 10
  • 43
  • 55
Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • 2
    Do the phrases "pass by value" and "pass by reference" mean anything to you? – Beta Sep 25 '13 at 18:16
  • @Beta yes mean what it should mean, but as you can see string variables are global not local, so is it needed to pass them by reference again? – Inside Man Sep 26 '13 at 07:10

3 Answers3

6

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
Community
  • 1
  • 1
Longo
  • 76
  • 3
2

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) {
    ...
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
2
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.