Program to swap two numbers using call by reference

What is Call by Reference?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
Lets see the code to swap two numbers using call by reference method:
 

CODE:

#include <iostream>

/* function declaration */
void swap(int *x, int *y);

int main ()
{
   /* local variable definition */
   int a = 100;
   int b = 200;

   cout<<"Before swap, value of a : n", a );
   cout<<"Before swap, value of b : n", b );

   /* calling a function to swap the values.
    * &a indicates pointer to a ie. address of variable a and
    * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b);

   cout<<"After swap, value of a : n", a );
   cout<<"After swap, value of b : n", b );

   return 0;
}

void swap (int *x,int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

OUTPUT:

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Leave a Reply