In C, there are two ways to pass parameters: passing by value: creating a copy of the parameter, and the function modifying the copy does not affect the original parameter. Pass by reference: Pass parameter reference, and function modification of the reference will affect the original parameter.
In C, function parameters can be passed to the function in the following two ways:
Pass by value
Pass by value passes a copy of the argument to the function, This means that any changes the function makes to the copy will not affect the original parameters.
Syntax:
##void foo(int x);
x It is passed to the
foo() function by value.
Pass by reference
Pass by reference passes the reference of the parameter to the function, which means that any changes made by the function to the reference are also reflected in the original parameter middle.Syntax:
##void foo(int &x);In this example,
It is passed to the foo()
function by reference.
Consider the following code:
// 按引用传递参数 void swap(int &a, int &b) { int temp = a; a = b; b = temp; } int main() { int x = 1; int y = 2; swap(x, y); std::cout << "x: " << x << std::endl; // 输出: 2 std::cout << "y: " << y << std::endl; // 输出: 1 return 0; }
In this example, the
swap() function receives by reference parameters a
and b
, so changes to them affect the original variables x
and y
.
The above is the detailed content of How to pass parameters of C++ function?. For more information, please follow other related articles on the PHP Chinese website!