无需先声明函数,我可以交换变量的值

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

本文关键字:交换 变量 我可以 声明 函数      更新时间:2023-10-16
#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;
}

上面的代码不能交换 A 和 B 的值。但我的问题是,当我忘记输入第三行"void swap(int, int(;",A 和 B 的值交换了!!为什么?

这是因为你有

using namespace std;

在源代码的开头。

这是一种糟糕的编程实践,您刚刚亲身经历了其后果。你告诉编译器你想调用std::swap,而没有任何线索你真的这样做了。

具有讽刺意味的是,因为你的 swap(( 版本不能正常工作,但std::swap可以工作;所以你在错误的印象下操作,认为你的代码正在工作,而事实并非如此。

切勿在代码中使用"使用命名空间 std;"。只是忘记了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;
}

不需要无效掉期

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