[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

changing variable values

Posted on 2003-11-08
3
Medium Priority
?
224 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
[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
  • Learn & ask questions
  • 2
3 Comments
 
LVL 5

Accepted Solution

by:
mtmike earned 80 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

by:msaa
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

by:mtmike
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
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 opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Suggested Courses

650 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