Here is a neat trick to swap two variables without using a third one. I’ve learned it from Patrick Greussay when I was studying AI. If memory serves me well, he discovered it while reviewing some satellite management code at MIT. I’ve seen it again later in some IBM code. It is using the beauty of the xor logic operator, and works on any same length bit fields, regardless of how you re-interpret them. In addition to a basic example, I am also illustrating the method using a union with floats to demonstrate this. Used with vector registers and SIMDs, it can be very handy. In particular, if you throw in some masking bit-ops, you can preserve any bit field from being swapped. So, next time memory is sparse or too far, why don’t you a = a ^ b; b = b ^ a; a = a ^ b;
void
swap ( int* a, int* b )
{
*a = *a + *b;
*b = *a – *b;
*a = *a – *b;
}
aldo núñez just had to re-activate your comment (spam filter :)). Didn’t try your approach, but I see you are using additions. This has an overflow problem. Works only with certain set of inputs.
Jamel Tayeb It works. And yes, it can produce overflow for some inputs….
Carmel Gafa it depends. As mentioned at the end of the post, in some applications, you do not have the memory or it is too far from your execution engine. You may also be in the situation where you want to reduce your register pressure and loading your registers is too expensive vs. the extra micro-ops (typically in long vector ops). But your question is the right approach, it may not have a positive trade off in normal cases, it really depends 🙂
Aldo Nike างที่เราจะได้ไม่ครบทุกชิ้นมีการเปลี่ยนชื่อใหม่แล้ว
Chonlada Kongkam the same time. I am not going on