Swapping Two Values Using Pointer in C

The basic concept of swapping two values in any programming language is by introducing another temporary variable. The logic is simple

temp = a;
a = b;
b = temp;

The above is the basic logic which shows how two values can be swapped. But here we are going to write the same progam using pointers.

The program using pointers is shown below,

#include<stdio.h>
#include<conio.h>
void swap(int*, int*);
int main()
{
    int a, int b;
    printf("Enter Two Numbers That are to be Swapped: ");
    scanf("%d %d", &a, &b);
    swap(&a, &b);
    printf("\na = %d, b = %d", a, b);
}
void swap(int *x, int *y)
{
    int t;
    t = *x;
    *x = *y;
    *y = t;
}

Output:

Enter Two Numbers That are to be Swapped: 10 20
a = 20, b = 10

As we know, functions can return only one value. So we have to modify the actual arguments of the function. The actual arguments are modified by passing the address of a and b. And when we are using the pointers(i.e., *) in our formal arguments, we are actually accessing the values of a and b directly. And the pointers are modifying the values. This method is known as Call by Reference.

Add a Comment