swap two integers
📝 CThis snippet exchanges the values of two integer variables without using a temporary variable, leveraging XOR bitwise operations for an efficient in-place swap.
C
void swap(int a, int b) { if (a != b) { a ^= b; b ^= a; a ^= b; }
}
Comments
Why would you rely on XOR swap when modern compilers already optimize the classic temp-variable swap into register moves, and XOR swap can fail if a and b refer to the same memory location?
I've actually seen this pattern cause a hard-to-find bug in a signal handler where the two pointers ended up aliased.