Hi,

I really don't understand why a^=b^=a^=b will swap the values of a and b. How does it work?

thnx

Printable View

- 04-21-2002NutshellWhy ^ will swap values?
Hi,

I really don't understand why a^=b^=a^=b will swap the values of a and b. How does it work?

thnx - 04-21-2002Shiro
a ^= b ^= a ^= b

is the same as

a ^= b

b ^= a

a ^= b

which can be written as

a = a xor b

b = b xor a = b xor (a xor b) = a

a = a xor b = (a xor b) xor a = b - 04-21-2002Salem
- 04-21-2002Nutshell
I konw the outcome. But how come it'll swap two values?

- 04-21-2002ygfperson
A= 1101

B= 0011

a = a ^ b = 1101 ^ 0011 = 1110

b = b ^ a = 0011 ^ 1110 = 1101

a = a ^ b = 1110 ^ 1101 = 0011

a is b's value

b is a's value - 04-21-2002Shiro
>I konw the outcome. But how come it'll swap two values?

Just follow the calculations and you'll see why, it's the result of the definition of the xor operation. If I am correct it only applies to integer values and not to floating point values. - 04-21-2002llieroXOR
the ^ means XOR or exclusive OR

or usually abbreviated XOR. will turn a bit on only

if the bits being compared are diff. for e.g.

127^127 is

0 1 1 1 1 1 1 1

^

0 1 1 1 1 0 0 0

-------------------------

0 0 0 0 0 1 1 1

in general, bitwise ANDs ORs and XORs apply their operations directly to each bit in the variable individually. for this conditions

bitwise operators are not usually used in conditional statements

the way relational and logical operators are.

i hope i did well...

but i think prelude has a good point of view in here..

thnx - 04-21-2002golfinguy4
Did it wrong.

127^127=0 - 04-21-2002llierooh really?
i did not did it wrong...

the book did it wrong...

if you think your better than the book, then publish your own

i just copied it from th book - 04-21-2002stautze
I was taught swaping values with xor is a favorite trick in assembly code, but I had never thought of using it in C. Nice.

- 04-21-2002Salem
Written out in long format

1. a = a ^ b

2. b = a ^ b

3. a = a ^ b

If you expand 2 (by substitution of a), you end up with the expression

b = ( a ^ b ) ^ b;

Now anything xor'ed with itself is zero, and anything xor'ed with 0 is itself...

we have

b = a ^ 0 // the b's cancel out giving us 0

Hence

b = a // half the swap completed

Now do the same thing with 3

a = ( a ^ b ) ^ a // remember that b is now a from the previous result

This reduces to

a = b ^ 0

therefore

a = b // the swap is complete

Voila! - 04-21-2002Prelude
To save myself some typing, here is a link. :)

http://www.cscene.org/CS9/CS9-02.html

-Prelude - 04-21-2002Nutshell
Thnx, understood it now everyone...

- 04-21-2002Prelude
>Thnx, understood it now everyone...

Good, now do us all a favor and don't adopt it as your favorite swap routine. :D

-Prelude - 04-21-2002Nutshell
Why? Any side effects?