Write a function which interchanges the value of two integers passed to it.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

void swap(int*, int*);

int main(int argc, char ** argv) {

    int a, b;
    printf("Enter a: ");
    scanf("%d", &a);
    printf("Enter b: ");
    scanf("%d", &b);
    swap(&a, &b);    // Parameter passing by reference
    printf("a: %d, b: %d\n", a, b);
    return 0;
}

void swap(int* a, int* b) {
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

When you compile and execute the above program it produces the following result on Linux:

Enter a: 5
Enter b: 4
a: 4, b: 5

Brief Explanation

  • The program begins by requesting two integers a and b.
  • scanf function reads the numbers and assigns them to the int variables a and b
  • The function swap interchanges the values of a and b. In swap, we are passing our parameters by reference I.e the addresses of variables a and b. This means that the function swap directly modifies the variables a and b.
  • The value of variable a is first assigned to a temporary variable tmp. Then the value of b is assigned to the location referenced by variable a. Finally, tmp is now assigned to the location referenced by variable b.
  • Because this parameter passing is done by reference, the change is effected in the main program and the swap function doesn't return any value.
  • The function printf is used to print the new values of a and b respectively.

Add comment


Security code
Refresh