PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     c++, pass-by-reference, pass-by-value, string     No comments   

Issue

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?


Solution

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?.



Answered By - Adrian Mole
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing