basics · beginner · ~15 min
Use XOR's self-inverse property to swap without a temp; learn why aliased pointers break the naive form.
Swap the two integers behind two pointers using the classic XOR trick — no temporary variable.
Implement void swap_xor(int *a, int *b) that exchanges the values *a and *b using XOR, without declaring a temporary. It must stay correct when the two pointers alias the same object (a == b), in which case the swap is a no-op, and when the two values are already equal.
Two non-NULL int * pointers, a and b.
No return value. After the call, *a holds the old *b and vice versa.
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 (aliased: must NOT zero it out)
a == b): the naive three-XOR sequence zeroes the value, so you must guard against it.a == b.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 pointers, a and b.
No return value; the pointed-to values are swapped in place.
No temporary variable. Must be safe when a == b (guard the aliasing case).
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.