+ 8

# a^=b^=a^=b; how this statement swaps the values of a & b?

5 Answers

+ 11

b xor (a xor b) = (b xor b) xor a = 0 xor a = a
(a xor b) xor a = (a xor a) xor b = 0 xor b = b
Basically, this exploits the fact that you need only two of the three values between a, b, and (a xor b) to be able to get the third value. Incidentally, you can swap the content of two variables by cycling through those 3 values.
If we set c = (a xor b), then we have the following relations:
a xor b = c
a xor c = b
b xor c = a
XOR is very handy in cryptography, and starting with the One Time Pad, aka the most simple crypto scheme with perfect security, which is just an xor between the message and the key (unfortunately, since the key has to be as long as the message and can't be reused, this is not practical to use in real life most of the time).
Handy if you just want basic obfuscation, too.

+ 10

^ expression is used for xor which is an logic gate and used in programming to get bitwise result for any operation this is done for swapping the value in the example like this way :-
a= 55=> 110111 (binary)
b = 5=> 000101 (binary)
And according to XOR if bits are same return 0 and if bits are different return 1.
So
a^=b;
110111
^ 000101
-----------------
110010
-------------------
a=110010=50
This will store in a.
Then b^a store in b.
b^=a;
000101
^ 110010
-------------------
110111
-------------------
b=110111=55
Then a^b again store in a.
a^=b;
110010
^ 110111
--------------------
000101
--------------------
So it store 5 in a
And values are swapped.
Else everything is explain by Zen and Rowsejđ

+ 5

Using XOR is strange, and I canât explain the behaviour, but I have made a code to show it working step-by-step: https://code.sololearn.com/cGpG8jn6CCWj/?ref=app

+ 2

If you want no warning:
a^=b;
b^=a;
a^=b;

0

so it's going like (a^=(b^=(a^=b))) ;
the operation starts from the innermost part!
great,.. thanks everyoneđ