Solved

# changing variable values

Posted on 2003-11-08
218 Views
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
Question by:msaa
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 5

Accepted Solution

mtmike earned 20 total points
ID: 9708183
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

ID: 9708206
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

ID: 9708240
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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
###### Suggested Courses
Course of the Month8 days, 1 hour left to enroll