ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-152 min read

Learn how to swap two numbers in C using temporary variables, arithmetic operations, bitwise XOR, and pass-by-reference pointers.

Overview

Swapping the values of two variables is one of the most common fundamental operations in algorithms, especially in sorting routines such as Bubble Sort and Quick Sort.

In C, swapping can be implemented in several ways:

  1. Using a temporary variable with pointers (Industry Standard).
  2. Using arithmetic addition and subtraction (without extra variable).
  3. Using bitwise XOR operations (without extra variable).

1. Pass-by-Reference with Pointers (Standard)

Because C uses pass-by-value by default, swapping variables inside a separate function requires passing their memory addresses using pointers:

c (ISO Standard)
#include <stdio.h>

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

int main() {
    int x = 15;
    int y = 40;

    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;
}

Expected Output

text (ISO Standard)
Before Swap: x = 15, y = 40
After Swap:  x = 40, y = 15

2. Bitwise XOR Swap (No Extra Memory)

The XOR swap algorithm uses the identity x ⊕ x = 0 and x ⊕ 0 = x:

c (ISO Standard)
#include <stdio.h>

void swapXOR(int *a, int *b) {
    if (a != b) { /* Protect against aliasing the same memory address */
        *a = *a ^ *b;
        *b = *a ^ *b;
        *a = *a ^ *b;
    }
}

int main() {
    int num1 = 100;
    int num2 = 250;

    printf("Before XOR Swap: num1 = %d, num2 = %d\n", num1, num2);
    swapXOR(&num1, &num2);
    printf("After XOR Swap:  num1 = %d, num2 = %d\n", num1, num2);

    return 0;
}

Method Comparison

MethodExtra MemorySafe from Overflow?Best Use Case
Temporary VariableO(1) (1 integer)YesGeneral production code
Bitwise XOR0 extra bytesYesLow-memory embedded registers
Arithmetic (+/-)0 extra bytesNo (can overflow INT_MAX)Math puzzles only

Related C Examples & Tutorials