C Program to swap two numbers using pass by reference



In this tutorial we will be learning another use of pointer to swap two numbers using pass by reference.

C Program to swap two numbers using pass by reference

#include<stdio.h>
#include<conio.h>

void swap(int *num1, int *num2);

void main() {
   int x, y;

   printf("\nEnter First number : ");
   scanf("%d", &x);

   printf("\nEnter Second number : ");
   scanf("%d", &y);

   printf("\nBefore Swaping x = %d and y = %d", x, y);
   swap(&x, &y); // Function Call - Pass By Reference

   printf("\nAfter Swaping x = %d and y = %d", x, y);
   getch();
}

void swap(int *num1, int *num2) {
   int temp;
   temp = *num1;
   *num1 = *num2;
   *num2 = temp;
}

Output :

Enter First number : 12
Enter Second number : 21

Before Swaping x = 12 and y = 21
After Swaping x = 21 and y = 12

See Output and Download »

Explanation : swap two numbers using pass by reference

In case of pass by reference, we are passing the address of the variables to the function.

swap(&x, &y); // Function Call - Pass By Reference

Consider the above line of code, in this we have passed the address of the variables to the function swap(). In this case while writing the function definition we need to accept those parameters as function argument –

void swap(int *num1, int *num2)

See how variable from main function is related with variables from swap function using following table –

Variable in main() Variables in swap()
Address of Variable 'x' Equals to num1
Address of Variable 'y' Equals to num2