Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why swap() can work well when I don't call it with two pointer?

#include <iostream>

using namespace std;

void swap(int *a, int *b) {
    *a = *a^*b;
    *b = *a^*b;
    *a = *a^*b;
}

int main()
{
    int array[]={1,9,2,8,3,7};
    for(int i=0; i<6; i++)
        cout<<array[i];
    cout<<endl;
    swap(array[1], array[4]);
    for(int i=0; i<6;i++)
        cout<<array[i];
    cout<<endl;
    return 0;
}

above is a test sample. I find if I use swap(array[1], array[4]);, it also swaps the values of two positions in array. But this confuses me, because the function swap() needs two pointers, not two integer values.

Thanks for your help:)

like image 471
city Avatar asked Jan 24 '13 19:01

city


1 Answers

using namespace std;  

This is your culprit. When you import the std:: namespace, you get every identifier declared in that namespace, potentially including std::swap.

Thus you are invoking std::swap<int>(int&,int&) (from the standard library) and not ::swap(int*,int*) (from your program.)

The moral of the story: never say using namespace std;. It's just too big.

like image 114
Robᵩ Avatar answered Sep 22 '22 21:09

Robᵩ