3
#include <iostream>

using namespace std;

void swap(int, int);

int main()
{
    int a=10;
    int b=20;

    swap (a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

void swap(int x, int y)
{
    int t;
    t = x;
    x = y;
    y = t;
}

those code above can't swap the value of a and b. but my question is , when I forgot to type the third line "void swap(int, int); " , the values of a and b swaped !! why?

Jing Guo
  • 39
  • 3

3 Answers3

7

It's because you have

using namespace std;

At the beginning of your source code.

This is a a bad programming practice, whose consequences you just experienced, first hand. You told the compiler that you want to invoke std::swap, without having any clue that you actually did that.

It's ironical, because you version of swap() won't work right, but std::swap does; so you were operating under the mistaken impression that your code was working, when it didn't.

Never use "using namespace std;" with your code. Simply forget that this part of the C++ language ever existed.

Community
  • 1
  • 1
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0
#include <iostream>

using namespace std;


int main()
{
    int a = 10;
    int b = 20;
    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    swap(a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    return 0;
}

void swap is unnecessary

Eitan
  • 3
  • 5
-1

If you put the function definition above main then you don't need a prototype otherwise you do need it and the compiler should give you an error if you don't have a prototype