swap (char *p, char *q)
{
	printf ("%c\t%c\n", *p, *q);
	*p ^= *q ^= *p ^= *q;
	printf ("%c\t%c\n", *p, *q);
}

int main (int argc, char *argv[])
{
	if (argc < 2)
	{
		printf ("\nSyntax: ./a.out str\n\n");
		exit (1);
	}
	
	char *p, *q, temp;
        p = q = argv[1];
	
	while (*++q);
	q--;

	while (p < q) swap (p++, q--);

	printf ("%s\n", argv[1]);

	return 0;
}

I am facing problem with the EX-OR statement in swap function, where it worked for other types like int, float.

Please any body help me..

What do you actually intend to do? When I ran your code, for an input "abcde" I got an output "edcba". What is the problem you're finding with swap()?

Just one piece of advice. Avoid writing codes like those in line 19 and 22. "++" operator may give different results with different compilers in case of post and pre increment.

Edited 4 Years Ago by subith86: n/a

but line 4 is not giving desired result in my compiler gcc version 4.4.4 20100630 (Red Hat 4.4.4-10) (GCC)

the trace i am getting is..

[rp@localhost #]$ ./strrev_inplace abcde
a	e
	a
b	d
	b

[rp@localhost #]$

I don't know why this fails for you. Can you try the swap using a temp variable, instead of XOR.

temp = *q;
*q = *p;
*p = temp;

I don't know why this fails for you. Can you try the swap using a temp variable, instead of XOR.

temp = *q;
*q = *p;
*p = temp;

then with this it is working..
but I want to know the behavior of my compiler with the statement in line 4, as now a days I am interested at this type of instructions and troubling my compiler.. Can you suggest some tools through which I can peep into the compiler, or compiled code..

Here's a suggestion
Why not use a modern compiler instead of carrying the burden of an old compiler?

Edited 4 Years Ago by zeroliken: n/a

*p ^= *q ^= *p ^= *q;

This statement invokes undefined behavior by modifying an object multiple times between sequence points. While cute, the correct form of an XOR swap is as follows:

*p ^= *q;
*q ^= *p;
*p ^= *q;

Notice how it's broken down into separate statements; the end of a statement introduces a sequence point. You can also use the comma operator if you want to be clever, but it's not recommended for readability purposes:

*p ^= *q, *q ^= *p, *p ^= *q;
This article has been dead for over six months. Start a new discussion instead.