Three ways to do a swap

Submitted by:Tim Kelly

Date added:01 August, 2016

Category:C++

3 Examples way to do a swap

Tags: swap

Code Snippet:

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;
}
 
 

Comments