Home  >  Article  >  Backend Development  >  The essential difference between passing by value and passing by reference in C++

The essential difference between passing by value and passing by reference in C++

PHPz
PHPzOriginal
2024-04-12 12:00:02534browse

The difference between value passing and reference passing in C: value passing creates a copy of the parameter and will not affect the original variable; reference passing directly operates the parameter, and the modification is reflected in the original variable. Practical case: exchanging two integer values. Passing by value will not exchange, but passing by reference will.

C++ 值传递和引用传递的本质区别

The essential difference between value passing and reference passing in C

In C, when passing function parameters, there are two Main choices: pass by value and pass by reference. The basic difference between these two passing methods is that passing by value creates a copy of the parameters, while passing by reference directly operates on the passed parameters.

Value passing

In value passing, a copy of the parameter value is passed to the function. This means that any modifications the function makes on the copy of the arguments passed will not affect the original variables.

void PrintValue(int num) {
  num++;
}

int main() {
  int x = 5;
  PrintValue(x);  // 传递 x 的副本
  cout << x;  // 输出 5,因为原始值不受影响
}

Pass by reference

In pass by reference, the reference of the parameter passed to the function is passed to the function. This means that the function operates directly on the passed arguments and any modifications will be reflected in the original variables.

void PrintReference(int& num) {
  num++;
}

int main() {
  int x = 5;
  PrintReference(x);  // 传递 x 的引用
  cout << x;  // 输出 6,因为原始值已被修改
}

Practical case

Let’s take a practical case to illustrate the difference between value passing and reference passing: exchanging the values ​​of two integers:

Value transfer:

// 值传递不会交换原始变量的值
void SwapValues(int a, int b) {
  int temp = a;
  a = b;
  b = temp;
}

int main() {
  int x = 5, y = 10;
  SwapValues(x, y);
  cout << x << " " << y;  // 输出 5 10,原始值没有交换
}

Reference transfer:

// 引用传递交换原始变量的值
void SwapReferences(int& a, int& b) {
  int temp = a;
  a = b;
  b = temp;
}

int main() {
  int x = 5, y = 10;
  SwapReferences(x, y);
  cout << x << " " << y;  // 输出 10 5,原始值已交换
}

The above is the detailed content of The essential difference between passing by value and passing by reference 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