Latest web development tutorials

C ++ call by reference

C ++ function C ++ function

Reference to the calling method parameters, copy the address parameters to the formal parameters passed to the function.Inside the function, the call reference is used to access the actual parameters to use. This means that a modified form of the parameters affect the actual parameters.

Passed by reference value, the reference parameter is passed to the function, just like other values ​​passed to the function the same. Thus Accordingly, the following functionswap (), you need to declare a function parameter is a reference type, the function value for the parameter exchange points to two integer variables.

// 函数定义
void swap(int &x, int &y)
{
   int temp;
   temp = x; /* 保存地址 x 的值 */
   x = y;    /* 把 y 赋值给 x */
   y = temp; /* 把 x 赋值给 y  */
  
   return;
}

Now, let us pass by reference to the calling functionswap ():

#include <iostream>
using namespace std;

// 函数声明
void swap(int &x, int &y);

int main ()
{
   // 局部变量声明
   int a = 100;
   int b = 200;
 
   cout << "交换前,a 的值:" << a << endl;
   cout << "交换前,b 的值:" << b << endl;

   /* 调用函数来交换值 */
   swap(a, b);

   cout << "交换后,a 的值:" << a << endl;
   cout << "交换后,b 的值:" << b << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Before switching, a value: 100
Before switching, b values: 200
After an exchange, a value of: 200
Following the exchange, b values: 100

C ++ function C ++ function