Swap Variables Without a Temp: The XOR Trick Explained
This article introduces the XOR (exclusive OR) operation, explains binary representation of numbers, demonstrates how XOR can swap two integer values without a temporary variable, and provides a concise C code example illustrating the technique.
Understanding XOR
In digital computers every value is represented in binary, using only the digits 0 and 1. The XOR (exclusive OR) operation yields 0 when the two bits are the same and 1 when they differ.
Binary example
Consider the two 4‑bit numbers 1001 (decimal 9) and 1100 (decimal 12). Applying XOR bit‑by‑bit produces:
1001
1100
----
0101The result 0101 corresponds to decimal 5.
Swapping two integers with XOR
The XOR operation can exchange the values of two variables without allocating a temporary storage location. The sequence of three XOR assignments works as follows:
Combine the two values: a = a ^ b Recover the original value of a into b: b = a ^ b Recover the original value of b into a: a = a ^ b After these steps, the variables a and b have swapped their original contents.
C code demonstration
int handsome = 1;
int rich = 5;
handsome = handsome ^ rich;
rich = handsome ^ rich;
handsome = rich ^ handsome;Running this snippet changes handsome from 1 to 5 and rich from 5 to 1, achieving the swap without any extra variable.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
