it's much more obvious what you're doing if you DO use a temp variable, so why not just use it? This sounds like a homework problem, and if so, nobody here is going to want to just give it to you.
If you have some reason for doing it, you'll be hard pressed to convice me its a valid reason, but i'd like to hear it.
Here it is
You can try what Ramesh suggested, it will work fine with integer values however you won't get accurate results when dealing with doubles and floats (Check the code below). The safest way is to use a third 'temp' variable as fred suggested
[ January 12, 2004: Message edited by: Vicken Karaoghlanian ]
[Vicken]: Actually it could be done in one line only, yes ONE LINE ONLY. However there is a small problem... it will work on C/C++ compilers only, it is an operator preceding thing i guess.
a = (b = (a = b ^ a) ^ b) ^ a;
a = (b ^= (a ^= b)) ^ a;
The key is that the last time ^ is executed, it needs the latest value of a as one of its arguments. If we write
a ^= b^= a ^= b;
that's equivalent to
a ^= (b ^= (a ^= b));
a = a ^ (b = b ^ (a = a ^ b));
and the problem is that when that bold a is evaluated, it uses the original value of a - rather than the value after the other operations have been evaluated. Java always evaluates left-hand operands before right-hand operands, even if it can't perform the operation itself until after both left and right sides have been evaluated. So the solution is to rearrange the order so that bold a is after everything else:
a = (b = b ^ (a = a ^ b)) ^ a;
Which has many equivalent forms, including the two I showed initially.
[ January 12, 2004: Message edited by: Jim Yingst ]
Originally posted by Elouise Kivineva:
But exactly because of this:
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." -- Martin Fowler
I think the
x = x+y;
y = x-y;
x = x-y;
answer might have been a better solution.
I was showing klisie what options she had, i didn't say it was the best way to do it...