C++ Call by Reference
The method of passing parameters to a function,Call by Referencecopies the address of the reference to the formal parameter. Inside the function, the reference is used to access the actual arguments to be used in the call. This means that modifying the formal parameter affects the actual argument.
Passing by reference, the parameter reference is passed to the function just like passing other values to a function. Therefore, accordingly, in the following functionswap()you need to declare the function parameters as reference types. This function is used to swap the values of the two integer variables pointed to by the parameters.
// 函数定义
void swap(int &x, int &y)
{
int temp;
temp = x; /* 保存地址 x 的值 */
x = y; /* 把 y 赋值给 x */
y = temp; /* 把 x 赋值给 y */
return;
}
Now, let's call the function by passing values by referenceswap():
Example
When the above code is compiled and executed, it produces the following results:
交换前,a 的值: 100 交换前,b 的值: 200 交换后,a 的值: 200 交换后,b 的值: 100
Key Points
- Reference Definition: by using
&symbol to define a reference type, for exampleint &ref。 - pass-by-reference: Use reference types in the function parameter list, so that modifications inside the function affect the actual variables passed in.
- Avoid copy overhead: Passing by reference avoids the copy overhead when passing large objects, improving efficiency.
Application scenarios of call by reference
- Modify external variables: As shown in the example above, modify the passed-in variables through the function.
- reduce overhead: Especially when passing large objects or complex data structures, passing by reference can avoid unnecessary copy operations.
- Return Value Optimization: Returning a function's local variable by reference avoids the overhead of copying the return value.
Call by reference is an important technique in C++ that can improve the efficiency and flexibility of code. Understanding and mastering call by reference is very helpful for writing efficient C++ programs.
other extensions