Forums Register Login

Swap the variables!!

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
Oh, and if you really want to be sick about it, try this:
x ^= y ^= x ^= y;
Joe
+Pie Number of slices to send: Send
Joe, you could slide those into the SCJP forum sometime
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Hi all
How about floats instead of int. Try this.
I think she's lovely. It's this tiny ad that called her crazy:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 694 times.
Similar Threads
swap without using temp variable
Help with array List
Swapping two object in array
Java Questions in Interview
How will u swap three variable without using temp variable !??
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:52:32.