Latest web development tutorials

C ++ call-by

C ++ function C ++ function

To thetraditional values of parameters passed to call thefunction, copy the actual values of the parameters to the formal parameters of the function. In this case, a modified form of the parameters within the function will not affect the actual parameters.

By default, C ++ using thecall-by-waysto pass parameters. Generally, this means that the code within the function does not change the actual parameters used to call the function. Functionswap () is defined as follows:

// 函数定义
void swap(int x, int y)
{
   int temp;

   temp = x; /* 保存 x 的值 */
   x = y;    /* 把 y 赋值给 x */
   y = temp; /* 把 x 赋值给 y */
  
   return;
}

Now, let us by passing actual arguments to call the 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:

交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 100
交换后,b 的值: 200

The above example shows that, although a change in the function and the value of b, but in fact, a and b values ​​are not changed.

C ++ function C ++ function