Hi,
Why does the statement z ^= true produce a false when the previous produces a true ?
bool v = true;
bool z = false;
z ^= v;
Console.WriteLine(z);
z ^= true;
Console.WriteLine(z);
OUTPUT
======
True
False
Hi,
Why does the statement z ^= true produce a false when the previous produces a true ?
bool v = true;
bool z = false;
z ^= v;
Console.WriteLine(z);
z ^= true;
Console.WriteLine(z);
OUTPUT
======
True
False
^ Means XOR, XOR is defined as true if one but not both sides are true, and is defined as false in every other case.
So
z ^= v means z = false ^ true, which means true
z ^= true means z = true ^ true, which is false
Note that ^= changes the value of the variable in the first and second statement
false XOR true = true, then you set z to true; true XOR true = false, then you set z to false.
The truth table for XOR
(^
) is
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
The operation lhs ^= rhs
is basically just a short-hand for lhs = lhs ^ rhs
. So, in your first application of ^=
you alter the value of z
, which (in accordance with the definition of ^
) changes the outcome of the second application.
An expression of the form x ^= y
is evaluated as x = x ^ y
The result of x ^ y
(XOR) is true
if and only if exactly one of its operands is true.
conclusion: x ^= true will produce true when x == true.