-1

So I have a swap function which have pointers as parameters. I understand the correct way to use the function is with swap(&n1, &n2). However, for this case I'm learning the difference between passing in the address of the variable, and the value directly.

My question is,

1 - Why does it still swap my variables, although I gave it the value to the function instead of its address?

2 - Why does my cout in my swap function not print, but the swap still happens?

When I use swap(&n1, &n2), the cout prints properly. I just want to know why the 2 scenarios above happen.

Thank you for your time.

#include <iostream>
#include <string> 
using namespace std;

void swap(int *value1, int *value2)
{
    int temp = *value2;
    *value2 = *value1;
    *value1 = temp;

    cout << endl <<"After swapping in swap function" << endl;
    cout << "Value of value1 = " << *value1 << endl;
    cout << "Value of value2 = " << *value2 << endl;
}

int main(int argc, char const *argv[])
{
    int n1,n2;
    cout << "Enter two numbers: " << endl;
    cin >> n1 >> n2;

    cout << "Before swapping in main function :" << endl;
    cout << "Value of num1 = " << n1 << endl;
    cout << "Value of num2 = " << n2 << endl;

    swap(n1,n2);

    cout << endl << "After swapping in main function : " << endl;
    cout << "Value of num1 = " << n1 << endl;
    cout << "Value of num2 = " << n2 << endl;    

    return 0;
}
Ethan
  • 1
  • 2
  • 4
    `using namespace std;` potentially leads to bugs and confusion. It did so here. `swap(n1,n2)` calls `std::swap`. When you do `using namespace std;` you must be aware of all names you pull in, which is basically impossible because they are too many – 463035818_is_not_an_ai Aug 22 '23 at 08:23
  • 2
    If someone ever told you that `using namespace` is bad, this is the reason why. – Quimby Aug 22 '23 at 08:25
  • In case you didn't get it. your code is not calling your swap function. Instead it is calling `std::swap`, that's why you don't see the output from your function, and why the swap still works. The reason `std::swap` is being called is because of `using namespace std;`. Experienced programmers do not use this, and your code is an example of why. – john Aug 22 '23 at 08:28
  • swapping two values is rather common as example for using pointers. However, its a very poor example, because you should not write this function but rather use `std::swap` and if you do write it anyhow you should not be using pointers but references. In general, if you do you pointers instead of references you must consider the case of nullptr. If you don't you could have used references – 463035818_is_not_an_ai Aug 22 '23 at 08:29

0 Answers0