• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swap the variables!!

 
Ravi Kumar Ravuru
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1376
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1376
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, and if you really want to be sick about it, try this:
x ^= y ^= x ^= y;
Joe
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe, you could slide those into the SCJP forum sometime
 
Joe Pluta
Ranch Hand
Posts: 1376
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
How about floats instead of int. Try this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic