XOR swap: Swaping the values of 2 variables.

This tip submitted by John Rambo on 2013-02-03 17:45:25. It has been viewed 1069 times.
Rating of 0.0 with 0 votes



I am not going to be explaining how XOR works, so I suggest you google "C bitwise operators" and learn about them.


In a tutorial I found, it states this: \" ^ The bitwise-exclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.\"


Here's the code:
/* This is a XOR swap. It works
by using the XOR bitwise operator 
to compare variable values. */

#include 

int main(int argc, char *argv[])
{
	int i = 6;  //0110 in binary.
	int y = 12; //1100 in binary.

	printf("i = %d, and y = %d\n", i, y);

	i ^= y; // i = |1010|                                      |1010|
	y ^= i; // y = |0110|, because we're comparing y to new i. |1100|
	i ^= y; // i = |1100| 

	printf("i = %d, and y = %d\n", i, y);

	return 0;
}




More tips

Help your fellow programmers! Add a tip!