a short question

This is a discussion on a short question within the C Programming forums, part of the General Programming Boards category; Hi!
How dose this code work?
what dose it mean?
/* C trick to swap n1 and n2 */
n1^=n2^=n1^=n2;...

I'll give you a hint. Assuming n1 and n2 to be integral types (char, int, long, unsigned), you're doing exclusive OR operations. Work it out on paper with ones and zeros. Remember that evaluation is grouped from right to left.

Note that this only works if n1 and n2 are distinct numbers. I.e. *p ^= *q ^= *p ^= *q fails miserably if p and q are pointing at the same number. It's generally better to use a third-party, temporary variable. Using a third-party variable works for 'all' datatypes (I'm talking about C++ here), it makes your code more readable, and it makes your code more generalized, instead of relying on the particular behaviors of integers.

Compilers with optimisations turned on can recognize both forms of swapping, so one is not necessarily faster than the other.

That thread doesn't show the example where the xor's are chained together in a single expression. I should also point out that a ^= b ^= a ^=b is undefined due to multiple side effects:

"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored."

> and doesn't use an temporary variable (thus faster):
I very much doubt it.
Every time I've tried these "cute" methods, all they do is confuse the compiler optimiser (as well as the average reader).

[...]

Stick to using a temporary - it always works, it works with any type and the compiler optimiser will see what you are doing. With any luck, it will rearrange the following code to effectively eliminate the swap from ever happening.

For those who missed it, repeat after me: "we're not in the 70's, we're not in the 70's, ..."