Latest web development tutorials

C ++ pointer call

C ++ function C ++ function

Pointer to call the function to pass parameters to copy the address parameters to the formal parameters.Inside the function, the address used to access the call actual parameters to use. This means that a modified form of the parameters affect the actual parameters.

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

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

For more details of the C ++ pointer, visit the C ++ pointer section.

Now, let's call the functionswap pointer by traditional values ():

#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;

   /* 调用函数来交换值
    * &a 表示指向 a 的指针,即变量 a 的地址 
    * &b 表示指向 b 的指针,即变量 b 的地址 
    */
   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