Skip to main content

Swap two values using pointers

Short answer

To swap two variables via a function, pass their addresses (call by reference). The function receives two pointers, dereferences them to exchange values using a temporary variable. Main calls swap(&x, &y); prints before (e.g., 15, 40) and after (40, 15).

Write a program using pointer to swap the value of two variables where the swapping operation is performed in separate function.

To change the original variables inside a function, their addresses are passed (call by reference). The function receives two pointers and exchanges the values stored at those addresses using a temporary variable.

#include <stdio.h>

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

int main(void)
{
    int x, y;
    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap : x = %d, y = %d\n", x, y);
    return 0;
}

Sample run

Input: 15 40

Enter two numbers: Before swap: x = 15, y = 40
After swap : x = 40, y = 15

If the values were passed instead of the addresses, only copies would be swapped and x and y would stay unchanged in main().

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →