# Swapping variable values without creating a new one

Recently, I was faced with a question that asked me to swap variable values without creating an extra variable.

i.e. A = 10, B = 20. How store 20 to A and 10 to B?

The solution is:

``````A = A + B     #new value of A=30
B = B + A     #new value of B=50
A = B - A     #new value of A=20
B = B - 2 * A #new value of B=10
``````

so A = 20 and B = 10

Does this algorithm have a known name?

That is a longer and less efficient variant of XOR swap algorithm. I'll just reiterate most-commonly known solutions here from the wiki:

``````# solution 1
A = A + B
B = A - B
A = A - B

# solution 2 (^ is XOR)
A = A ^ B
B = B ^ A
A = A ^ B
``````

@PEMapModder

On the second last line, there is no difference between `A^B` and `B^A` right? Why swap them?

There is no difference between them. I think Wiki swaps them for historical reasons: For machine instructions that use 2 registers for binary operations (source and target/destination, unlike MIPS which uses 3 registers for binary ops), you would write the XOR solution as follows:

``````XOR A B       # A = A ^ B
XOR B A       # B = B ^ A
XOR A B       # A = A ^ B
``````
• What's wrong with `A, B = B, A`? That's how it works in a lot of the languages I am familiar with. – Jörg W Mittag May 17 '16 at 15:30
• I think OP was challenged to find a solution to the problem without using parallel assignment. That would've been too easy. – mostruash May 17 '16 at 15:35
• What "OP" means? – dellasavia May 17 '16 at 16:54
• "Original Poster", ie, you. – Useless May 17 '16 at 16:58
• Might be worth noting that the XOR solution should be immune to over-/under-flow, whereas solution 1 and OP's solution might be affected. – 8bittree May 17 '16 at 17:14