Three ways to do a swap source codeThis snippet submitted by David Nielsen on 2005-05-30. It has been viewed 40700 times.Rating of 5.6 with 415 votes void swap1(int a, int b) { int c = a; a = b; b = c; } void swap2(int a, int b) { // notice: swap2(x, x) doesn't work // undefined behavior using this method with floats a = a ^ b; b = a ^ b; a = a ^ b; //or... //a ^= b; //b ^= a; //a ^= b; } void swap3(int a, int b) { // notice: overflow should work, but behaviour is undefined a = a + b; b = a - b; a = a - b; } More C and C++ source code snippets |