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

Swap the two integers behind two pointers using the classic XOR trick — no temporary variable.

Task

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.

Input

Two non-NULL int * pointers, a and b.

Output

No return value. After the call, *a holds the old *b and vice versa.

Example

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)

Edge cases

  • Aliased pointers (a == b): the naive three-XOR sequence zeroes the value, so you must guard against it.
  • Equal values and large negative magnitudes must still swap correctly.

Rules

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

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 pointers, a and b.

Output format

No return value; the pointed-to values are swapped in place.

Constraints

No temporary variable. Must be safe when a == b (guard the aliasing case).

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.