Bitwise XOR Swap in C

Level 4127 keystrokes

Swaps two values using XOR bitwise operation without a temporary variable.

C code

// Two values to swap
1int a = 25, b = 17;
// Print original values
2printf("Before: a=%d, b=%d\n", a, b);
// XOR swap: a now holds a^b
3a = a ^ b;
// b becomes original a (a^b^b = a)
4b = a ^ b;
// a becomes original b (a^b^a = b)
5a = a ^ b;
// The values are swapped without a temporary variable (a=17, b=25)
6printf("After: a=%d, b=%d\n", a, b);

Output

Before: a=25, b=17
After: a=17, b=25
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • =× 9
  • ,× 7
  • ;× 6
  • "× 4
  • %× 4
  • ^× 3
  • :× 2
  • (× 2
  • )× 2
  • \× 2

More C examples at level 4

← C typing practice