#include <iostream>
// function declaration void swap(int *, int *);
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;
/* calling a function to swap the values.*/
swap(&a, &b);
cout << “After swap, value of a << a << endl;
cout <<“After swap, value of b << b << endl;
}
// function definition to swap the values, void swap(int *x, int *y)
{
int temp;
temp = *x; // assign to temp from the value at address x
*x = *y; // put value at address y into x
*y = temp; // put value of temp into value at the address y
}
The output of the above program is:
Before swap, value of a :100 Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
In the above program, swap() function is declared with two arguments of type integer pointers. During the function call memory address of variable, ‘a’ and variable ‘b’ is passed as actual arguments, and formal arguments are pointer ‘x’ and pointer Y takes the address of ‘a’ and ‘b’ variables respectively. In the body of the swap function, the pointer operator is used to access the value at the location. Here the memory location of ‘a’ and ‘b’ are accessed by the pointers V and Y and produces the output as shown above.