basics · beginner · ~15 min
Use XOR's self-inverse property to swap without a temp; learn why aliased pointers break the naive form.
Implement void swap_xor(int *a, int *b) that swaps the integers pointed to by a and b without allocating a temporary variable.
a == b (aliased pointers) — the swap is then a no-op.*a == *b initially.int x=1, y=2; swap_xor(&x, &y); // x==2, y==1
int x=5, y=5; swap_xor(&x, &y); // x==5, y==5
int x=7; swap_xor(&x, &x); // x==7 (aliasing must NOT clobber to 0)
a == b) must NOT corrupt the value — the naive XOR-swap clobbers to 0 if you don't guard.The classic XOR-swap is a rite of passage. It only matters in code-golf or extremely register-starved embedded contexts these days, but understanding why it works deepens your grip on XOR. (Production: just use a temporary — it's clearer and the compiler optimises both forms identically.)
Two non-NULL int *.
The pointed-to values are swapped.
No temporary variable. Must be safe when a == b.
void swap_xor(int *a, int *b) { /* TODO */ }
Forgetting the aliasing guard — *a ^= *b; *b ^= *a; *a ^= *b; zeros out the value when a == b.
Aliased pointers; equal values; large magnitudes.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.