📍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>
2
3// Function receives pointers (addresses)
4void swap(int *a, int *b) {
5 int temp = *a; // Get value at address a
6 *a = *b; // Put b's value at a's address
7 *b = temp; // Put temp at b's address
8}
9
10int 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 addresses
16
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.