Yesterday, I’ve seen the following function.
static void swap (int *p, int *q) {
*p -= *q;
*q += *p;
*p = *q - *p;
}
In which case this function does not work? I think there is potentially an overflow problem, and it can be also inefficient. Is there anything else?
The overflow issue is not a “maybe”, it’s there for sure: when you exchange a high-magnitude negative with a large positive, you get an overflow, which is undefined behavior according to the standard.
But most importantly, there is absolutely no point to use this (or the xor trick) in place of the usual exchange (through a temp variable) for reasons of readability.