Gaganrajdeep Singh
Gaganrajdeep Singh

Reputation: 39

Why is this working? I cannot understand the logic of this swapping

int main() {
    // Complete the program
    string a,b;
    getline(cin,a);
    getline(cin,b);
    cout<<a.size()<<" ";
    cout<<b.size();
    string c=a+b;
    cout<<endl<<c;

    swap(a[0],b[0]);
    cout<<endl<<a<<" "<<b;
    return 0;
}
void swap(string s1,string s2){
    string temp=s1;
    s1=s2;
    s2=temp;
}

Well the target is to swap the first element of both strings, but I created a general function for that and even got it right. But, unexpectedly, I didn't use pass by reference or pointer! Even then, the changes are permanent when I try to output a and b in the end!

Logically it shouldn't work but it is working. Is it something to do with the strings?

Upvotes: 1

Views: 128

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51835

This is almost certainly due to the fact that, somewhere in code that you have not shown us, you have this line (or something very similar):

using namespace std;

With this line included, then that very namespace std defines a function as follows:

void swap(_Ty& _Left, _Ty& _Right);

Where the _Ty template is replaced with char in your swap(a[0],b[0]); call.

Add a simple cout << "My Swap" << endl; line to your swap function, and you'll see it's not being called.

Highly recommended reading: Why is "using namespace std;" considered bad practice?.

Upvotes: 8

Related Questions