Home  >  Article  >  Backend Development  >  How to pass function parameters in C++

How to pass function parameters in C++

王林
王林Original
2024-04-13 17:33:01839browse

C There are three ways to pass function parameters: passing a copy by value, passing a reference by reference, and passing a pointer by pointer. Passing by value does not affect the actual parameters, passing by reference and pointer do.

C++ 函数参数的传递方式

C How to pass function parameters

In C, function parameters can be passed by reference, pointer or value. Here are introductions and practical examples of each passing method:

Pass-by-value

Pass a copy of the function argument. Any modifications to the copy will not affect the actual parameters passed.

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

Output:

Before swap: a = 10, b = 20
After swap: a = 10, b = 20

Pass-by-reference

Pass a reference to a function parameter. Any modification to the reference will affect the actual parameters passed.

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

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10

Pass-by-pointer

Pass the pointer of the function parameter. Any modification to the memory pointed to by the pointer will affect the actual parameters passed.

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

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10

The above is the detailed content of How to pass function parameters in C++. 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