M'kay.
Code:
#include <stdio.h>
void badswap(char *a, char *b)
{
(*a) = (*a) ^ (*b);
(*b) = (*b) ^ (*a);
(*a) = (*a) ^ (*b);
}
int main()
{
char *p, *q, text[] = "hello world";
puts(text);
for ( p = text, q = &text[sizeof text - 2]; p <= q; ++p, --q )
{
badswap(p,q);
}
puts(text);
return 0;
}
/* my output
hello world
dlrow
*/
See how swapping an object with itself can do unwanted things?
Now there is no need to swap a value with itself, so the test could be written p < q. But the point was that this XOR trick is an old hack that has more drawbacks and few advantages compared with the simple straightforward swap.
Code:
#include <stdio.h>
void goodswap(char *a, char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
int main()
{
char *p, *q, text[] = "hello world";
puts(text);
for ( p = text, q = &text[sizeof text - 2]; p <= q; ++p, --q )
{
goodswap(p,q);
}
puts(text);
return 0;
}
/* my output
hello world
dlrow olleh
*/
And for me, goodswap generates less code than badswap.