Why does this program swap the values?
Asked Answered
R

2

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)

Reply answered 7/5, 2011 at 5:21 Comment(1)
Basically, this is a dupe of https://mcmap.net/q/22970/-how-to-use-an-iterator/…, although you wouldn't know this unless you know the answer.Vyborg
O
38

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.

Onagraceous answered 7/5, 2011 at 5:24 Comment(1)
You can call you swap() by ::swap(x, y)Christyna
B
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.

Blackjack answered 7/5, 2011 at 5:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.