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:
- Using a temporary variable with pointers (Industry Standard).
- Using arithmetic addition and subtraction (without extra variable).
- 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
| Method | Extra Memory | Safe from Overflow? | Best Use Case |
|---|---|---|---|
| Temporary Variable | O(1) (1 integer) | Yes | General production code |
| Bitwise XOR | 0 extra bytes | Yes | Low-memory embedded registers |
| Arithmetic (+/-) | 0 extra bytes | No (can overflow INT_MAX) | Math puzzles only |
Related Tutorials & Algorithms
- Deep dive into pointer dereferencing in Pointers in C Guide.
- See swap used in practice in Bubble Sort in C.