>>16
yeah, that is a good point. If a program tries to swap a variable with itself, that is a wasted operation and should be avoided. It's just a subtle difference in the behavior of XOR swap and the other, temporary values swap.
>>15
you could cast the T* to a char* to an array of sizeof(T) chars, and then XOR swap each character. To get better performance, you could use a larger data type, like int or long, but then you'll need to handle if sizeof(T) isn't divisible by sizeof(int) or sizeof(long).
Also, I've heard that using something that the compiler will recognize as a swapping operation is better, as there might be assembly instructions that are intended for swapping memory.
>>28
using
#define SWAP(a,b) if(1) {typeof(a) c = a; a = b; b = c;}
would get
[code]
if(condition)
SWAP(a,b);
to work, but then
if(condition)
SWAP(a,b);
else
b = a;
would fail, as it would expand to:
if(condition) {
if(1) {
typeof(a) c = a;
a = b;
b = c;
}
else {
b = a;
}
}
and so now the code in the else statement will never be executed, as it is paired with if(1).
the
do{}while(0) is one way to do it, and it's pretty popular. If makes the macro look externally like a void procedure.