Three ways to do a swap

Submitted by:Jhon Smith

Date added:27 September, 2017

Category:C++

C/C++ source code - Three ways 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