Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 326
ipkiss Avatar asked May 07 '11 05:05

ipkiss


2 Answers

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.

like image 107
James McNellis Avatar answered Nov 09 '22 00:11

James McNellis


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.

like image 38
user541686 Avatar answered Nov 09 '22 01:11

user541686