why won't this work

in regard this post:
http://www.cplusplus.com/forum/lounge/86612/#msg465228

i tried to do this:
1
2
3
4
5
6
7
8
9
#include <string.h>

void reverse(char s[])
{

    for (int i = 0, j = strlen(s)-1; i < j; i++, j--) {
        s[i]^=s[j]^=s[i]^=s[j];
    }
}


but when i try and use it it does not work, am i making a stupid mistake somewhere?
s[i]^=s[j]^=s[i]^=s[j];
Why this? As far as I see, this is going to do no such reversing.
I don't really know, but I noticed that...
i < j; should be i <= j;
If there's an error it's in the xor group.

Looking at wikipedia it should be like:

1
2
3
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];

So it should work as you wrote it?
Last edited on
s[i]^=s[j]^=s[i]^=s[j]; is undefined (for scalar types, such as char)
s[i]^=s[j]^=s[i]^=s[j]; is undefined (for scalar types, such as char)


then why does this work:
1
2
3
4
5
6
7
#include <iostream>
int main() {
	char a='a', b='b';
	a^=b^=a^=b;
	std::cout<<a<<' '<<b;
	return(0);
}

i < j; should be i <= j;

why, if i==j, then they are pointing to the same character, why swap them?

@Resident Biscuit
it is a technique I learnt in A to Z of C I was also confused at first, but it is quite useful - well at least with numbers
> but when i try and use it it does not work
¿how are you using it?
i try your code, i can work ,
make sure the param 'a' is not readonly.
this works:
1
2
3
4
5
6
7
8
9
void reverse(char s[])
{

    for (int i = 0, j = strlen(s)-1; i < j; i++, j--) {
        s[i]^=s[j];
		s[j]^=s[i];
		s[i]^=s[j];
    }
}


thanks guys :)
Last edited on
That works, but it's obfuscated and slow, compared to the example linked in the first post.
Topic archived. No new replies allowed.