Solved

changing variable values

Posted on 2003-11-08
3
211 Views
Last Modified: 2010-04-15
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..
0
Comment
Question by:msaa
  • 2
3 Comments
 
LVL 5

Accepted Solution

by:
mtmike earned 20 total points
Comment Utility
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.
0
 

Author Comment

by:msaa
Comment Utility
Thank you very much it really worked! but I have no clue whats going on? could you please explain it?
0
 
LVL 5

Expert Comment

by:mtmike
Comment Utility
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.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now