I have tested the code below
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main() {
int a, b;
a = 5;
b = 10;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "&a = " << &a << endl;
cout << "&b = " << &b << endl;
swap(a, b);
cout << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int *x, int *y){
cout << "Hello" << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
int temp;
temp = *x;
*x = *y;
*y =temp;
}
I know it should pass &a and &b to swap and that works as expected. However, above codes seem work as well. Results are:
a = 5
b = 10
&a = 0x7ffeea1648d8
&b = 0x7ffeea1648d4
a = 10
b = 5
Questions are:
If the swap function is implemented why there is no info printed out?
If swap function is not implemented why the values swap?
Your code is not doing what you think it does. To understand, try to compile this:
void foo(int* x) {}
int main() {
int x = 42;
foo(x);
}
You will get an error because you cannot pass an int to a function that expects an int*. Your code still works because of
using namespace std;
and because there is a std::swap(int&,int&) that matches your call (hence you wont see an error for the swap you wrote) and your
swap(a, b);
actually calls the standard function.
Take it as a lesson and try to avoid using namespace std;. This is just one problem that you can encounter when you use it.
Moreover I would suggest you to use references instead of pointers. Pointers can be null, but if one of the parameters to your function is null, it does not make sense to swap anything. With references the code looks much nicer (well subjective, but maybe you can agree):
void swap(int& x, int& y){
int temp;
temp = x;
x = y;
y =temp;
}
However, you shouldnt be writing a swap in the first place, but use std::swap instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With