Three ways to do a swap source code

This snippet submitted by David Nielsen on 2005-05-30. It has been viewed 29657 times.
Rating of 6.3 with 319 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

Add a snippet!