0

I tried to print out something in the void swap function, but nothing happened. Why is it? It can print out something in the add function or the main function, though. Thank you for your help!

#include <iostream>
using namespace std;

int add(int num1, int num2)
{
    int sum = num1 + num2;
    cout << "Hello" << endl;
    
    return sum;
}


void swap(int *a, int *b) {
    int c = *a;
    cout << "Hello" << endl;
    *a = *b;
    *b = c;
}


int main()
{
    int num1 = 10;
    int num2 = 20;

    cout << "Num1: " << num1 << endl;
    cout << "Num2: " << num2 << endl;

    swap(num1, num2);

    cout << "Num1: " << num1 << endl;
    cout << "Num2: " << num2 << endl;

    system("pause");

    return 0;
}
  • 9
    `swap(num1, num2);` uses `std::swap`, not your function. You would need `swap(&num1, &num2);` to match your overload. – Jarod42 Sep 02 '22 at 15:35
  • 19
    This is why `using namespace std` is bad for you – DownloadPizza Sep 02 '22 at 15:36
  • 2
    Read more here on this topic: [why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?rq=1) – Stack Danny Sep 02 '22 at 15:42
  • If I change my swap function into swap(num1, num2) and get rid of all the pointers in the function, would it override std::swap? Because when I run it in this case, it is actually using my swap function and printing out the "Hello". – William Lin Sep 03 '22 at 14:53

0 Answers0