+ 3
Values swapping in C#
Anybody please explain what is happening in this program Hi, Anybody please help me understand what is happening in this program a = a ^ b ^ (b = a); How this like is swapping both of the values at once https://code.sololearn.com/cVO10ccDJ4No/
4 Answers
+ 2
Mahad Ahmed the expression evaluates from left to right. Understand that bitwise xor (^) is a bit toggle. Wherever there is a 1 bit in the right operand, it will toggle the same bit from the left operand to its opposite value. A 0 bit causes no change. a^0 = a
When you xor a number with itself, you get zero. a^a = 0
When you xor a number with another number, a^b, you get an intermediate value c that can be decoded back into either a or b by xor-ing with its opposite number.
c^a = b
c^b = a
Now the swap:
First a^b , we'll call it c.
Then c^(b = a). This is an assignment statement that reassigns b to a and then has a final value of a. It is equivalent to:
b = a; //b is now a
c^(a)
Expanding c, which encodes the original b,
(a^b)^(a) = a^b^a = b^a^a = b^0 = b
And that b gets assigned to a.
a = b //a is now b
Swapped!
+ 1
-- or
(a,b) = (b,a);
+ 1
SoloProg Thanks yes it can be done with a tuple but I need to understand how it is swapping the both values
+ 1
Brian Thank you so much. Very well explained and easy to understood answer. Thanks š