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;
}