Created
February 7, 2011 22:34
-
-
Save andy722/815394 to your computer and use it in GitHub Desktop.
Various ways to swap two integer values in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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