C 函數參數傳遞有三種方式:按值傳遞副本,按引用傳遞引用,按指標傳遞指標。按值傳遞不影響實際參數,依引用和指標傳遞則會影響。
C 函數參數的傳遞方式
在 C 中,函數參數可以透過參考、指標或值傳遞。以下是對每種傳遞方式的介紹和實際範例:
按值傳遞 (pass-by-value)
傳遞函數參數的副本。對副本的任何修改都不會影響傳遞的實際參數。
void swap(int x, int y) { int temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; std::cout << "Before swap: a = " << a << ", b = " << b << std::endl; swap(a, b); // a 和 b 的副本被传给 swap std::cout << "After swap: a = " << a << ", b = " << b << std::endl; return 0; }
#輸出:
Before swap: a = 10, b = 20 After swap: a = 10, b = 20
依引用傳遞 (pass-by-reference)
傳遞函數參數的參考。對引用的任何修改都會影響傳遞的實際參數。
void swap(int &x, int &y) { int temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; std::cout << "Before swap: a = " << a << ", b = " << b << std::endl; swap(a, b); // a 和 b 的引用被传给 swap std::cout << "After swap: a = " << a << ", b = " << b << std::endl; return 0; }
#輸出:
Before swap: a = 10, b = 20 After swap: a = 20, b = 10
以指標傳遞 (pass-by-pointer)
傳遞函數參數的指標。對指標所指向記憶體的任何修改都會影響傳遞的實際參數。
void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int a = 10, b = 20; std::cout << "Before swap: a = " << a << ", b = " << b << std::endl; swap(&a, &b); // a 和 b 的指针被传给 swap std::cout << "After swap: a = " << a << ", b = " << b << std::endl; return 0; }
輸出:
Before swap: a = 10, b = 20 After swap: a = 20, b = 10
以上是C++ 函式參數的傳遞方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!