Home >Backend Development >C++ >What are the C++ function parameter passing mechanisms?

What are the C++ function parameter passing mechanisms?

王林
王林Original
2024-04-11 12:30:01580browse

C The function parameter passing mechanism is divided into passing by value and passing by reference. Passing by value creates a copy of the parameter value. Modifications to the copy do not affect the original parameter. Used for basic data types. Pass by reference passes the parameter address directly, allowing the function to modify the original parameter, for complex types.

C++ 函数参数传递机制有哪些?

C function parameter passing mechanism

In C, the parameter passing mechanism determines how the function receives parameters passed from the caller . There are two mechanisms: pass-by-value and pass-by-reference.

Pass by value

Pass by value creates a copy of the parameter value, which is stored in the function’s stack frame. Any modifications to the copy will not affect the actual parameters in the calling function. Passing by value is typically used for primitive data types (int, float, etc.).

Code example:

void increment(int value) {
  value++; // 修改局部副本
}

int main() {
  int a = 5;
  increment(a);
  std::cout << a << std::endl; // 输出 5,因为 a 的值没有改变
}

Pass by reference

Pass by reference does not create a copy of the parameter, but passes The address of the parameter itself is passed by reference. This allows the function to directly modify the original parameters in the calling function. Pass by reference is typically used for complex types (objects, containers, etc.).

Code example:

void increment(int& value) {
  value++; // 修改原始参数
}

int main() {
  int a = 5;
  increment(a);
  std::cout << a << std::endl; // 输出 6,因为原始参数被修改
}

Practical case

Pass by value example:Calculate function parameters squared.

int square(int value) {
  return value * value;
}

int main() {
  int a = 5;
  int result = square(a);
  std::cout << result << std::endl; // 输出 25,因为按值传递不会影响 a
}

Pass by reference example: Exchange the values ​​of two function parameters.

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

int main() {
  int a = 5;
  int b = 10;
  swap(a, b);
  std::cout << "a = " << a << ", b = " << b << std::endl; // 输出 a = 10, b = 5,因为按引用传递修改了原始参数
}

The above is the detailed content of What are the C++ function parameter passing mechanisms?. 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