To refactor a code section to make it more easily readable and understandable.
The following code shows one way to swap the values in two integers a and b. The caret (^) operator takes the exclusive or (XOR) of the two values. The comments to the right explain how this method works.
// Swap a and b. Let A and B be the original values. b = a ^ b; // b = A ^ B a = a ^ b; // a = A ^ (A ^ B) = (A ^ A) ^ B = B b = a ^ b; // b = B ^ (A ^ B) = (B ^ B) ^ A = A
This is a clever piece of code. It lets you swap two values without needing to waste memory for a temporary variable.