In C, there are four ways to pass parameters: 1. Pass by value (copy) 2. Pass by reference 3. Pass by constant reference 4. Pass by pointer. Passing by value and passing by reference are used to modify the original value, constant reference is used for read-only access, and passing by pointer is used to operate the memory address.
C Function parameter passing methods
In C, there are many ways to pass data to functions. Depending on whether a copy of the value or a reference to the value is passed, parameter passing methods are divided into the following types:
1. Pass by Value
Pass a copy of the value; modifications to the copy will not affect the original value. Declaration method:
void f(int a); // 传递 a 的副本
2. Pass by Reference
Pass the reference of the value, and modifications to the reference will affect the original value. Declaration method:
void f(int& a); // 传递 a 的引用
3. Pass by Constant Reference
is similar to passing by reference, but the value pointed to by the reference cannot be modified. Declaration method:
void f(const int& a); // 传递 a 的常引用
4. Pass by Pointer
Pass the pointer to the value. Modification of the value pointed to by the pointer will affect the original value. Declaration method:
void f(int* a); // 传递 a 的指针
Actual case:
The following is an example of a C function using pass-by-value and pass-by-reference:
#include <iostream> // 传值 void swapValue(int a, int b) { int temp = a; a = b; b = temp; } // 传引用 void swapReference(int& a, int& b) { int temp = a; a = b; b = temp; } int main() { int x = 1, y = 2; std::cout << "Before swapValue: x = " << x << ", y = " << y << std::endl; swapValue(x, y); std::cout << "After swapValue: x = " << x << ", y = " << y << std::endl; std::cout << "Before swapReference: x = " << x << ", y = " << y << std::endl; swapReference(x, y); std::cout << "After swapReference: x = " << x << ", y = " << y << std::endl; return 0; }
Output result:
Before swapValue: x = 1, y = 2 After swapValue: x = 1, y = 2 Before swapReference: x = 1, y = 2 After swapReference: x = 2, y = 1
Note:
The above is the detailed content of What are the methods of passing function parameters in C++?. For more information, please follow other related articles on the PHP Chinese website!