Hello Folks, There are two variables suppose int x=10,y=20.I want to swap the variables without using a temporary variable.How can we do that?Please help me out. Regards, Ravi
Joe Pluta
Ranch Hand
Joined: Jun 23, 2003
Posts: 1376
posted
0
Welcome to boolean logic 101. x = x^y; y = x^y; x = x^y; Nothing could be simpler . Joe P.S. Back in the olden days, we actually had to do this kind of stuff to save registers and avoid costly memory accesses. Honest!
Joe Pluta
Ranch Hand
Joined: Jun 23, 2003
Posts: 1376
posted
0
Oh, and if you really want to be sick about it, try this: x ^= y ^= x ^= y; Joe
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
Joe, you could slide those into the SCJP forum sometime
For those of us who aren't really familiar with those forums, Barry, what exactly is the purpose of the SCJP forum, for example? How would I "slip this into" the forum? Just a question that might stimulate a little more participation from those of us who currently don't spend time in the certification forums. Joe
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
posted
0
Not as cool as Joe's, but as a colleague of mine pointed out, this also works: x = x + y y = x - y x = x - y