开发者

Why does "x ^= true" produce false in this example?

开发者 https://www.devze.com 2022-12-15 08:16 出处:网络
Why does the statement z ^= true produce a false when the previous produces a true ? bool v = true; bool z = false;

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.WriteLin开发者_运维百科e(z);

OUTPUT
======
True
False


Because it changes the value of z in the first statement.


Because:

false ^ true == true
true ^ true == false

See http://en.wikipedia.org/wiki/Xor


^ 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


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.


false XOR true = true, then you set z to true; true XOR true = false, then you set z to false.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消