📍⚡Beginner
Swap Two Numbers Using Pointers
Swap using pointers
Swap using pointers allows the function to modify the original variables. This is call by reference in C.
Program Code
swap_pointers.c
C
1#include <stdio.h>23// Function receives pointers (addresses)4void swap(int *a, int *b) {5 int temp = *a; // Get value at address a6 *a = *b; // Put b's value at a's address7 *b = temp; // Put temp at b's address8}910int main() {11 int x = 10, y = 20;12 13 printf("Before swap: x = %d, y = %d\n", x, y);14 15 swap(&x, &y); // Pass addresses16 17 printf("After swap: x = %d, y = %d\n", x, y);18 19 return 0;20}Output
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Why use pointers? In C, function arguments are passed by value (copied). Without pointers, swap would only modify local copies, not the original variables.
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials