語法書 / AA 競程語法書 上冊 / 第七單元 / Pass by value vs Pass by reference

7.3 Pass by value vs Pass by reference

圖 7-1:傳值 vs 傳參考

當你在函式內修改參數時,要知道外面的變數會不會被改掉。這涉及到參數是「複製傳遞」還是「引用傳遞」。

Pass by value(值傳遞)

在預設情況下,函式參數是「值傳遞」:電腦會把你傳進去的變數值複製一份,函式內部操作的是這份複本,不影響外面的原變數。

Pass by reference(引用傳遞)

在參數型態後面加上 & 符號,就變成「引用傳遞」:函式操作的是外面的原變數,修改會直接反映到外面。

範例程式碼

#include<iostream>
using namespace std;

// 版本 1:Pass by value(預設)
void addByValue(int x) {
    x = x + 10;  // 只修改複本,不影響外面的變數
}

// 版本 2:Pass by reference(參數前加 &)
void addByReference(int &x) {
    x = x + 10;  // 直接修改外面的變數
}

int main() {
    int a = 5;

    // 測試 Pass by value
    addByValue(a);
    cout << "Pass by value: " << a << "\n";  // 還是 5

    // 測試 Pass by reference
    addByReference(a);
    cout << "Pass by reference: " << a << "\n";  // 變成 15

    return 0;
}

執行結果:

Pass by value: 5
Pass by reference: 15

實際場景:交換兩個變數的值

如果要在函式內交換兩個變數的值,必須用 &

// ✗ 不能交換(Pass by value)
void swapWrong(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
    // 交換的只是複本,外面的變數不變
}

// ✓ 能交換(Pass by reference)
void swapCorrect(int &x, int &y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 3, b = 5;
    swapWrong(a, b);
    cout << a << " " << b << "\n";  // 輸出 3 5(沒變)

    swapCorrect(a, b);
    cout << a << " " << b << "\n";  // 輸出 5 3(交換了)

    return 0;
}

動手試試看:定義一個 void reset(int &x) 函式把參數重設為 0,然後在 main() 中呼叫它,確認原變數真的被改了。