3 ms·
> At the hardware level, you can't swap two variables without using a third. There are situations where that's not true. Consider doing the register allocation
by cliffbean 14y ago
> At the hardware level, you can't swap two variables without using a third.
There are situations where that's not true. Consider doing the register allocation for code which does this:
void foo(int x, int y) {
for (/* stuff */) {
// swap x and y on each iteration
int t = x;
x = y;
y = t;
// do stuff with x and y
}
}
This is a situation where the code does a swap, and the register allocator can't optimize it away (without unrolling the loop). But we can use the XOR swap trick to swap x and y in place, without using a third register, which may make another register available which can live across loop iterations.
x ^= y
y ^= x
x ^= y
and we're done. No third register needed.
Of course, this is a really low-level trick useful in certain register allocation algorithms, not something that normal users should write in a high-level language.