Skip to content
Devtoolry

Basics · beginner

C Program to Swap Two Numbers

Swap two numbers in C with a temporary variable, then write a swap() function with pointers, and see why a swap function without pointers changes nothing.

Swapping two values needs a third, temporary variable in C. The more interesting part is putting the swap in a function: C passes arguments by value, so a function receives copies. To change the caller's variables, the function must receive their addresses, which is what pointers are for.

The program

C
#include <stdio.h>

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main(void) {
    int a = 5, b = 10;
    printf("Before: a = %d, b = %d\n", a, b);

    swap(&a, &b);
    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}
Output
Before: a = 5, b = 10
After:  a = 10, b = 5

How it works

  1. swap() takes two pointers, int *x and int *y: addresses of ints, not ints.
  2. *x reads the value at that address, so temp keeps the original value of a.
  3. *x = *y copies b into a, and *y = temp puts the old a into b.
  4. main passes &a and &b, the addresses of its variables, so swap changes them directly.

Another way: Why a swap without pointers fails

Here the function swaps its own copies, which disappear when it returns. a and b in main are untouched.

C
#include <stdio.h>

void broken_swap(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
    printf("Inside: x = %d, y = %d\n", x, y);
}

int main(void) {
    int a = 5, b = 10;
    broken_swap(a, b);
    printf("Outside: a = %d, b = %d\n", a, b);
    return 0;
}
Output
Inside: x = 10, y = 5
Outside: a = 5, b = 10

Common mistakes

  • Writing a = b; b = a;, which copies b into both and loses the original a.
  • Calling swap(a, b) instead of swap(&a, &b): the compiler warns that an int is passed where a pointer is expected.
  • The XOR trick (a ^= b; b ^= a; a ^= b;) sets both values to 0 when both pointers point to the same variable.

Try it yourself

  • Swap two doubles with a second function, then write one generic swap with void * and memcpy.
  • Rotate three variables a, b, c so that a gets b, b gets c and c gets a.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.