C++ Call by Pointer

C++ Functions

The method of passing arguments to a functionCall by Pointercopies the address of the argument to the formal parameter. Inside the function, the address is used to access the actual argument needed in the call. This means that modifying the formal parameter affects the actual argument.

Passing by pointer means the argument pointer is passed to the function, just like passing other values to a function. Accordingly, in the following functionswap()you need to declare the function parameter as a pointer type; 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;
}

For more details about pointers in C++, please visitC++ PointersChapter.

Now, let's call the function by passing values through pointers.swap():

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

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

C++ Functions

other extensions