Home > Backend Development > C++ > body text

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

王林
Release: 2024-04-19 12:33:02
Original
1090 people have browsed it

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

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

Practical case

Consider the following function:

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

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

Output:

10, 5
Copy after login

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!

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