#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))1. Don't be clever in our code base. Use a temp variable. 2. There's various dumb tricks with XOR, and possibly add/subtract if overflows don't break. 3. A sequence of several instructions where each of them requires the result of the previous one may not execute particularly fast on modern processors. Instruction/cycle counts -- like 3 -- are great when there's no pipeline and no cache, but otherwise pretty much useless. 4. The things you're swapping might be local variables, and when the compiler has -O <anything> specified, local variables start getting weird, and "swap" can sometimes be done in zero instructions, namely by the compiler noting that they have now been swapped and using the other one for the rest of the basic block. (or further dominated basic blocks for that matter) 5. If the things you're swapping are in main memory, or even if it's not in L1, you're going to be incurring a cost much greater than the temporary use of a register. (and, if you don't know where they are and it might be main memory, this might dominate the average runtime)
The answer is definitely not "three xors".
int x, y;
...
SWAP(x, y);
foo(x, y);
becomes int x, y;
...
foo(y, x);
(naturally, this is why I still eagerly await the arrival of a C compiler that has macros with LISP power)I don't know how every compiler works, but if you use Clang (or anything LLVM-based), it converts everything to Single Static Assignment (SSA) form:
int x1 = 42, y1 = 666;
...
int tmp = x1; x2 = y1; y2 = tmp; // SWAP(x, y)
foo(x2, y2);
In SSA form, the value of a variable does not change, so it ends up creating a bunch of "imaginary" variables to hold intermediate values. From there, it does optimizations, then figures out how best to allocate registers, and what needs to be stack-allocated.http://chaos-pp.cvs.sourceforge.net/chaos-pp/order-pp/exampl...
But I do not envy the poor soul who would have to maintain all this cleverness.
The very best candidates add: Because it's tricky, hard to read, limited in scope, and usually you can avoid swapping variables by changing their usage downstream. Besides, the best compilers will sort it out for you if you write it clearly and cleanly.
When I interview it's not the answers I listen to, it's the knowledge they expose, not of programming per se, but of good practices in programming.