Reputation: 1
The cout statement in function call swap is not executing. Why?
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
cout << "Value Swapped" << endl;
}
int main() {
int x = 400, y = 100;
swap(x, y);
cout << "x = " << x << " y = " << y << endl;
return 0;
}
I have expected below output:
Value Swapped
x = 100 y = 400
But the output I have got is:
x = 100 y = 400
Upvotes: 0
Views: 194
Reputation: 25516
using namespace std
imports another equally named function from namespace std
into global namespace, so you end up in having two overloads:
swap(int&, int&); // from std; actually a template instantiation
swap(int*, int*);
You call swap
as
swap(x, y);
Now consider: Which are the types of x
and y
, are they pointers? So decide yourself, which overload will get called?
If you hadn't imported the second overload via using namespace std
, which generally is considered bad practice anyway (well, you got a victim of the pitfalls of right away...), you would have ended up in a compilation error instead (integers aren't converted to pointers implicitly!).
To get your function called, you need to make pointers from:
swap(&x, &y);
// ^ ^
Actually, that would have worked even with the imported namespace (despite of being bad practice), as the imported overload is a template, yours an ordinary function, thus yours is considered the more specialised overload and thus will be preferred.
Upvotes: 0
Reputation: 93
Consider choosing a unique enough identifier name such that there will not be a conflict with a namespace
identifier (as in std::swap
). If you can't choose the name of your identifier, put it inside of a namespace
.
Secondly, if the compiler does not enforce the function declaration that you state, you should manually check to see that you passed the variables correctly (i.e., &x
and &y
instead of x
and y
).
Upvotes: 0
Reputation: 86506
You're not seeing "Value swapped" because your swap function never gets called. Instead, you're calling std::swap<int>
.
If you hadn't said using namespace std;
, you'd have found out that your swap
function is being passed integers, but was expecting pointers. Reason #1 not to use using namespace std;
-- you can easily end up not calling what you think you are. :)
Upvotes: 3
Reputation: 421
your function swap is expecting pointers as arguments, but you are passing integers. So instead of calling your function, it's calling the c++ swap function. To better understand this, change the function name 'swap' to any other name like 'swapp' and you'll see this error:
invalid conversion from int to int*
write swap(&x, &y) and you'll get your desired output
Upvotes: 0