Why does this program swap the values?
I have the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <conio.h>
#include <cstring>
#include <iomanip>
void swap(long a, long b)
{
long temp;
temp=a;
a=b;
b=temp;
}
int _tmain(int argc, _TCHAR* argv[])
{
int x = 5, y = 3;
cout << x ;
c开发者_开发问答out << y << endl;
swap(x, y);
cout << x ;
cout << y << endl;
getch();
return 0;
}
The program gives the output:
5 3
3 5
The program actually swaps the values! Why is that? The parameters of the swap()
are not pointers or references.
(I am using VS 2005)
Your swap
function isn't being called at all.
One of the Standard Library includes that you have included is pulling in <utility>
, which declares a function template named swap
in the std
namespace. Since you are using namespace std;
, that swap
function is being brought into the global namespace and it is called instead.
Why is std::swap
chosen instead of your swap
function? Your swap
function takes two long
s by value; to call that function, an integer promotion is required for each of the int
arguments.
std::swap
is a function template. It takes two references to T
, and when that function template is instantiated with T = int
, both arguments are an exact match. So, std::swap
is a better match than your function and it is therefore selected during overload resolution.
This is one reason that using namespace std;
is evil and should be avoided. If you remove the using directive, your function will be the only function available and it will be called.
Say long
instead of int
.
Your current code already has a better match for swap
, so it avoids the implicit conversion to long
, and instead uses the built-in swap
from the STL.
On a side note, this ambiguity is somewhat solved using overload sets (also here) in the language D.
精彩评论