10 Replies Latest reply on Jan 7, 2005 8:58 AM by 798906

# How do you swap two variables A and B without using a 3rd variable?

How do you swap two variables A and B without using a 3rd variable? No function or method allowed.

For example:

Given:

A = 35

B = 10

Result

A = 10

B = 35
• ###### 1. Re: How do you swap two variables A and B without using a 3rd variable?
How do you swap two variables A and B without using a
3rd variable? No function or method allowed.

For example:

Given:

A = 35

B = 10

Result

A = 10

B = 35
``````A = A + B  (A = 10 + 35 = 45)

B = A - B (B = 45 - 35 = 10)

A = A - B (A = 45 - 10 = 35)``````
• ###### 2. Re: How do you swap two variables A and B without using a 3rd variable?
if I read that response correctly, you end up with the same thing you started with. should be:
``````A = A + B  (A = 35 + 10 = 45)

B = A - B (B = 45 - 10 = 35)

A = A - B (A = 45 - 35 = 10)``````
• ###### 3. Re: How do you swap two variables A and B without using a 3rd variable?
although, frankly, I hope you aren't planning to write code like that... cuz it's generally better to write code that's more easily understood then to write tricks into the code.
• ###### 4. Re: How do you swap two variables A and B without using a 3rd variable?
You can also do it with the exclusive or bitwise operator...
a = a ^ b;
b = a ^ b; ((a ^ b) ^ b == a)
a = a ^ b; ((a ^ b) ^ a == b)

Cheers,
evnafets
• ###### 5. Re: How do you swap two variables A and B without using a 3rd variable?
So crossposted...
• ###### 6. Re: How do you swap two variables A and B without using a 3rd variable?
if I read that response correctly, you end up with
the same thing you started with. should be:
``````A = A + B  (A = 35 + 10 = 45)

B = A - B (B = 45 - 10 = 35)

A = A - B (A = 45 - 35 = 10)``````
Thanks for correciting me... I just took the numbers for example... the end result is same what is expected... Thanks anyways :-)
• ###### 7. Re: How do you swap two variables A and B without using a 3rd variable?
Why do you need this?
• ###### 8. Re: How do you swap two variables A and B without using a 3rd variable?
just out of curiousity
• ###### 9. Re: How do you swap two variables A and B without using a 3rd variable?
just out of curiousity
Forget it, its a pointless exercise. You would never ever do this in practice.
• ###### 10. Re: How do you swap two variables A and B without using a 3rd variable?
``A=(A^=B)^(B^=A);``