← Back to Gists

swap two integers

📝 C
dayi
dayi · Level 1 ·

This 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

1
algo_smith algo_smith

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?

0

I've actually seen this pattern cause a hard-to-find bug in a signal handler where the two pointers ended up aliased.