I heard from my friend that the best algorithm for the exchange is "(a ^ = b ^ = a ^ = b)" where a and b are two integers to be exchanged. but when I applied it using c, it led to a crash. can any of you wonderful people explain the possible reason for this? suggest the best algorithm for sharing. Thanks!!!! guys, I would like to know the reason for the failure.
this exchange trick is sometimes dangerous, I saw the wrong quicksort program using this swap, generating incorrect results. But a regular swap generates the right program.
, , tmp.
tmp = a; a = b; b = tmp;
a^=b^=a^=b; , , undefined. , , , a . , - , :
a^=b^=a^=b;
a
a ^= (b ^= a ^= b, b);`
:
b ^= a ^= b; a ^= b;
-, , - , .
. http://en.wikipedia.org/wiki/Swap_(computer_science).
, , XOR, , XOR.
. http://www.ibm.com/developerworks/linux/library/l-metaprog1.html .
, . . , , . XOR-, , .
int a = 10, b =5 ; a = a-b; b = b+a ; // b gets the original value of a a = b - a; // a gets the original value of b printf ("value : %d %d \n",a ,b) ;