views:

241

answers:

6

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
+19  A: 

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

Noon Silk
+1 for addressing the question, not the definition of XOR ;)
Alexis Abril
+7  A: 

^ 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

AlbertEin
+1  A: 

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

CaseyB
+15  A: 

Because:

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

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

Michael
+2  A: 

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.

Dirk
+1  A: 

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.

serhio