C++ Program to swap two numbers using call by reference

Here we will under how to swap a variable using call by reference then we will write a program to swap two numbers using call by reference method in C++ programming language.

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.

Here we have already discussed how to swap two numbers using Bitwise XOR ‘^’ and ‘+’ and ‘-‘ operators.
Lets see the code to swap two variables using call by reference method:

C++ Program to swap two numbers using call by reference:

#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

Comment below in case you want to discuss more about this program or suggestions.

1 thought on “C++ Program to swap two numbers using call by reference”

Leave a Comment