basics · beginner · ~15 min

Swap two integers using XOR (no temporary)

Use XOR's self-inverse property to swap without a temp; learn why aliased pointers break the naive form.

Challenge

Implement void swap_xor(int *a, int *b) that swaps the integers pointed to by a and b without allocating a temporary variable.

  • The function must work even when a == b (aliased pointers) — the swap is then a no-op.
  • The function must work even when *a == *b initially.

Examples

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)

Edge cases

  • Aliased pointers (a == b) must NOT corrupt the value — the naive XOR-swap clobbers to 0 if you don't guard.

Why this matters

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.)

Input format

Two non-NULL int *.

Output format

The pointed-to values are swapped.

Constraints

No temporary variable. Must be safe when a == b.

Starter code

void swap_xor(int *a, int *b) { /* TODO */ }

Common mistakes

Forgetting the aliasing guard — *a ^= *b; *b ^= *a; *a ^= *b; zeros out the value when a == b.

Edge cases to handle

Aliased pointers; equal values; large magnitudes.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.