Home > Backend Development > C++ > body text

How to pass function parameters in C++

王林
Release: 2024-04-13 17:33:01
Original
896 people have browsed it

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;
}
Copy after login

Output:

Before swap: a = 10, b = 20
After swap: a = 10, b = 20
Copy after login

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;
}
Copy after login

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10
Copy after login
Copy after login

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;
}
Copy after login

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template