簡體   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;
}

上面的代碼不能交換a和b的值。 但我的問題是,當我忘記鍵入第三行“void swap(int,int);”時,a和b的值會變換!! 為什么?

這是因為你有

using namespace std;

在您的源代碼的開頭。

這是一個糟糕的編程習慣 ,它只是你剛剛經歷的后果。 你告訴編譯器你要調用std::swap ,而不知道你實際上是這么做的。

這很諷刺,因為你的swap()版本不能正常工作,但std::swap會這樣做; 因此,您錯誤地認為您的代碼正在運行,而不是。

永遠不要使用“using namespace 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;
}

void swap是不必要的

如果你把函數定義放在main之上,那么你不需要原型,否則你確實需要它,如果你沒有原型,編譯器會給你一個錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM