10

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 ;
    cout << 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)

James McNellis
  • 348,265
  • 75
  • 913
  • 977
ipkiss
  • 13,311
  • 33
  • 88
  • 123
  • Basically, this is a dupe of http://stackoverflow.com/questions/2712076/how-to-use-iterator-in-c/2712125#2712125, although you wouldn't know this unless you know the answer. – sbi May 08 '11 at 06:14

2 Answers2

37

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 longs 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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
1

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.

user541686
  • 205,094
  • 128
  • 528
  • 886