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..

Recommended Answers

All 7 Replies

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.

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?

*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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.