• C

# changing variable values

Hi, I have  a question, which I solved but using 3 variables.. would like to see if its possible with only 2 variables?

the questions says, ask the user to input A and B then let the two variables exchange the values.. so if A is 10 and B is 5 >>> the result should be A = 5 and B = 10..
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You can use the XOR trick:

a ^= b;
b ^= a;
a ^= b;

But most machines have an XCHG instruction so the third variable is optimized out anyway.

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Author Commented:
Thank you very much it really worked! but I have no clue whats going on? could you please explain it?
Commented:
I will try...

It is based upon the fact the x ^ y ^ y = x, since y ^ y = 0 and x ^ 0 = x.

When you write the XOR sequence like this:

c = a ^ b
d = b ^ c
e = c ^ d

The final d and e will be:

d = b ^ c = a ^ (a ^ b) = a
e = c ^ d = (a ^ b) ^ (b ^ (a ^ b)) = b

It is a funny mathematical trick.
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.