C++ Call by Pointer
pass arguments to a function via thecall by pointermethod, which copies the argument's address to the formal parameter. Inside the function, that address is used to access the actual argument used in the call. This means modifying the formal parameter affects the actual argument.
To pass a value by pointer, the parameter pointer is passed to the function just like passing any other value. Therefore, correspondingly, in the function below swap() , 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.
// Function definition
void swap(int *x, int *y)
{
int temp;
temp = *x; /* 保存地址 x 的值 */
*x = *y; /* assign y to x */
*y = temp; /* assign x to y */
return;
}
For more details about pointers in C++, please visit the C++ Pointers section.
Now, let us call the function by passing values through pointers swap():
#include
using namespace std;
// Function declaration
void swap(int *x, int *y);
int main ()
{
// Local variable declaration
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 code above is compiled and executed, it produces the following result:
交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 200
交换后,b 的值: 100
C++ functions