Home  >  Article  >  Backend Development  >  The difference between passing values ​​and passing references in C++ function parameters

The difference between passing values ​​and passing references in C++ function parameters

王林
王林Original
2024-04-19 12:33:021091browse

C There are two ways to pass function parameters: value transfer and reference transfer: Value transfer: Create a copy of the local variable, and modifications to the copy will not affect the original variable. Pass by reference: Directly pass the reference to the original variable, and modifications to the reference variable are reflected in the original variable.

C++ 函数参数传递值和传递引用的区别

C The difference between passing values ​​and passing references for function parameters

Passing values

When a function parameter is passed by value, a copy of the local variable is created. Changes to this copy do not affect the original variable.

Syntax:

void function(int value);

Pass reference

When function parameters are passed by reference, pass the reference to the original variable directly. , instead of creating a copy. Changes to the reference variable will be reflected in the original variable.

Syntax:

void function(int& value);

Practical case

Consider the following function:

void swap(int& a, int& b) {
  int temp = a;
  a = b;
  b = temp;
}

This function is passed by reference Two integers are passed, so when the function swaps the values ​​of a and b, it also modifies the original variable in the main function.

Usage example:

int main() {
  int x = 5, y = 10;
  swap(x, y); // 交换 x 和 y 的值
  cout << x << ", " << y << endl; // 输出交换后的值
  return 0;
}

Output:

10, 5

The above is the detailed content of The difference between passing values ​​and passing references in C++ function parameters. 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