C++ Pointer Call
The pointer call method for passing parameters to a function involves copying the address of the parameter into the formal parameter. Inside the function, this address is used to access the actual parameter needed in the call. This means that modifications to the formal parameter will affect the actual parameter.
When passing values by pointer, the parameter pointer is passed to the function, similar to passing other values to the function. Consequently, in the following swap() function, you need to declare the function parameters as pointer types, which are used to swap the values of two integer variables pointed to by the parameters.
// Function definition
void swap(int *x, int *y)
{
int temp;
temp = *x; /* Save the value at address x */
*x = *y; /* Assign y to x */
*y = temp; /* Assign x to y */
return;
}
For more details on pointers in C++, please visit the C++ Pointers section.
Now, let's call the swap() function by passing values through pointers:
#include <iostream>
using namespace std;
// Function declaration
void swap(int *x, int *y);
int main ()
{
// Local variable declaration
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* Call the function to swap the values
* &a denotes pointer to a, i.e., address of variable a
* &b denotes pointer to b, i.e., address of variable b
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100