why won't this work

Script Coder (456)
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?
ResidentBiscuit (2645)
s[i]^=s[j]^=s[i]^=s[j];
Why this? As far as I see, this is going to do no such reversing.
EssGeEich (1007)
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
Cubbi (1925)
s[i]^=s[j]^=s[i]^=s[j]; is undefined (for scalar types, such as char)
Script Coder (456)
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
ne555 (4383)
> but when i try and use it it does not work
¿how are you using it?
uriza (1)
i try your code, i can work ,
make sure the param 'a' is not readonly.
Script Coder (456)
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
Cubbi (1925)
That works, but it's obfuscated and slow, compared to the example linked in the first post.
Registered users can post here. Sign in or register to post.