Skip to content

Instantly share code, notes, and snippets.

@andy722
Created February 7, 2011 22:34
Show Gist options
  • Save andy722/815394 to your computer and use it in GitHub Desktop.
Save andy722/815394 to your computer and use it in GitHub Desktop.
Various ways to swap two integer values in C
#include <stdio.h>
void swap(int *, int *);
void swap_xor(int *, int *);
int main() {
int a = 1, b = 2;
printf("a = %i, b = %i\n", a, b);
swap_xor(&a, &b);
printf("a = %i, b = %i\n", a, b);
return 0;
}
void swap(int *a, int *b) {
*a = *a + *b; // integer overflow
*b = *a - *b;
*a = *a - *b;
}
void swap_xor(int *a, int *b) {
if (a == b)
return;
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}
void swap_xor_short(int *a, int *b) {
if (a == b)
return;
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
void swap_xor_incorrect(int *a, int *b) {
*a ^= *b ^= *a ^= *b; // modification of lvalue w/out intervening sequence point
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment