Home >Backend Development >C++ >How to pass parameters of C++ function?

How to pass parameters of C++ function?

王林
王林Original
2024-04-18 21:45:02542browse

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.

C++ 函数的参数如何传递?

C How to pass function parameters

In C, function parameters can be passed to the function in the following two ways:

  • Pass by value
  • Pass by reference

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);

In this example,

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,

x

It is passed to the foo() function by reference.

Practical case:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn