What is the operator below ^? When to use it?
My programing language is C#.
^
is a Logical XOR Operator if the operands are bools, otherwise it's a Bitwise XOR Operator
Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.
http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx
It's the XOR operator. It's used in bitwise operations, where the result is true if the left side is true or the right side is true, but false if both are true or both are false. So 0xf8 ^ 0x3f
would be:
1111 1000
0011 1111
---------
1100 0111
Which is C7 in hexadecimal.
In general, if you're not doing bitwise arithmetic, you won't need to worry about it.
Example:
101 ^
110
-----
011 //Flip the first 2, keep the 3rd
Example:
int myMoney = 10;
int yourMoney = 50;
Swap(myMoney, yourMoney)
public void Swap(ref int a, ref int b) //No 'temp' variable necessary
{
a ^= b;
b ^= a;
a ^= b;
}
It is used in binary arithmetic. ** THIS IS ACTUALLY USEFUL **
Flip a bool (though, I'd rather use bool x = true; x != x;
Example:
public bool flip(ref bool b)
{
b ^= true;
}
I think of it as a binary operator just like ||, &&, etc...
If I were writing logic and ended up with:
if( (condition1 && !condition2) || (condition2 && !condition1) )
{
}
I might rewrite it as:
if( condition1 ^ condition2)
{
}
That said, I'd take it on a case by base basis and weigh the benefit of brevity vs. potential obfuscation due to relative obscurity.
Its Exclusive OR (XOR) operator as mentioned by others. Here is the truth table for XOR
P Q P^Q
T T F
T F T
F T T
F F F
Note that P^Q is equal to P!=Q. Sometimes P!=Q is used in the code instead of XOR operator.