Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Last active October 26, 2015 15:56
Show Gist options
  • Select an option

  • Save davepkennedy/b25456bf680bd640e53e to your computer and use it in GitHub Desktop.

Select an option

Save davepkennedy/b25456bf680bd640e53e to your computer and use it in GitHub Desktop.
Swap two numbers without an intermediate variable. Still takes as many statement as with one though…
Swap two numbers without an intermediate variable. Still takes as many statement as with one though…
Consider a = 5, b = 10
a = b0101
b = b1010
a = a ^ b -> b0101 ^ b1010 -> a = b1111 (15)
b = a ^ b -> b1111 ^ b1010 -> b = b0101 (5)
a = a ^ b -> b1111 ^ b0101 -> a = b1010 (10)
a = b1010 = 10
b = b0101 = 5
Values are now swapped. Easy.
#include <stdio.h>
#define SWAP(a,b) {a = a^b; b = a^b; a = a^b;}
int main(int argc, const char * argv[]) {
// insert code here...
int x = 3;
int y = 298;
printf("x = %d, y = %d\n", x, y);
SWAP(x,y);
printf("x = %d, y = %d\n", x, y);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment