简体   繁体   English

如果没有声明函数,我可以交换变量的值吗?

[英]without declaration the function first, I can swap the value of the variables?

#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. 上面的代码不能交换a和b的值。 but my question is , when I forgot to type the third line "void swap(int, int); " , the values of a and b swaped !! 但我的问题是,当我忘记键入第三行“void swap(int,int);”时,a和b的值会变换!! why? 为什么?

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. 你告诉编译器你要调用std::swap ,而不知道你实际上是这么做的。

It's ironical, because you version of swap() won't work right, but std::swap does; 这很讽刺,因为你的swap()版本不能正常工作,但std::swap会这样做; so you were operating under the mistaken impression that your code was working, when it didn't. 因此,您错误地认为您的代码正在运行,而不是。

Never use "using namespace std;" 永远不要使用“using namespace std;” with your code. 用你的代码。 Simply forget that this part of the C++ language ever existed. 简单地忘记这部分C ++语言曾经存在过。

#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 void swap是不必要的

如果你把函数定义放在main之上,那么你不需要原型,否则你确实需要它,如果你没有原型,编译器会给你一个错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM