call by value (傳值)

  • 在Call-by-Value中,函式的參數是被傳遞值的副本
  • 在函式內部,對參數的修改不會影響到原始的變數。

call by address (傳位置)

  • 傳了實際的記憶體位置進去function
  • 也是call by value的變形,但傳遞的是記憶體地址
  • 在函式內部,通過指標可以修改原始變數的值。

call by reference (傳參考)

  • 在Call-by-Reference中,函式的參數接受原始變數的參考(或記憶體位置)。
  • 在函式內部,對參數的修改會直接影響到原始的變數。
#include <iostream>

// Call-by-Value (值傳遞)
void incrementByValue(int value) {
    value++;
}

// Call-by-Reference using pointer (指標參考傳遞)
void incrementByPointer(int* ptr) {
    (*ptr)++;
}

// Call-by-Reference using reference (參考傳遞)
void incrementByReference(int& ref) {
    ref++;
}

int main() {
    int num = 10;

    incrementByValue(num);        // 傳遞值
    std::cout << "Call-by-Value: " << num << std::endl;  // 輸出:10

    incrementByPointer(&num);     // 傳遞指標參考
    std::cout << "Call-by-Pointer: " << num << std::endl; // 輸出:11

    incrementByReference(num);    // 傳遞參考
    std::cout << "Call-by-Reference: " << num << std::endl; // 輸出:12

    return 0;
}
傳值傳地址傳參考
incrementByValueincrementByPointerincrementByReference
傳入函式的東西整數值整數指標(指標變數)整數引用
原始的num不影響(因為是副本)會影響會影響