Swapping two values is a basic concept in programming. Using pointers in C, we can swap two values without returning them from a function. This tutorial explains how to swap two integers using call by reference with pointers.
Objective
- Use a function to swap two variables.
- Pass addresses of variables to the function using pointers.
- Perform the swap inside the function.
Example C Program
#include <stdio.h>
// Function to swap two values
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("Before swapping: x = %d, y = %d\n", x, y);
// Call the swap function
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
Sample Output
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
Explanation
swap()
takes two integer pointers as arguments.- Inside the function, dereference the pointers to access and swap actual values.
&x
and&y
pass the addresses ofx
andy
to the function.
Why Use Pointers for Swapping?
- Enables modification of original values.
- Efficient when working with large structures or arrays.
- Demonstrates the concept of call by reference.
Tip
You can use this logic to swap any data type by adjusting the function accordingly.
Example: float
, char
, or user-defined structures.
Conclusion
Using pointers to swap two values in C is a fundamental and powerful technique. It allows functions to modify variables directly and is commonly used in sorting algorithms and memory manipulation routines.
This program helps beginners understand how pointers can control and manipulate data directly.