# Why ^ will swap values?

This is a discussion on Why ^ will swap values? within the C Programming forums, part of the General Programming Boards category; Hi, I really don't understand why a^=b^=a^=b will swap the values of a and b. How does it work? thnx...

1. ## Why ^ 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

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

3. I konw the outcome. But how come it'll swap two values?

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

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

6. ## XOR

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

7. Did it wrong.

127^127=0

8. ## oh 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

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

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

11. To save myself some typing, here is a link.

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

-Prelude

12. Thnx, understood it now everyone...

13. >Thnx, understood it now everyone...
Good, now do us all a favor and don't adopt it as your favorite swap routine.

-Prelude

14. Why? Any side effects?

Page 1 of 2 12 Last
Popular pages Recent additions