OR, AND Operator - c#

Newbie question.
How to calculate the value of the formula A f B, where f - the binary function OR or AND?

There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...
cond1 && cond2 && cond3
If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...
cond1 || cond2 || cond3
If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.
The bitwise counterparts, & and | are not escaping.
Hope that helps.

Logical OR is ||, logical AND is &&.
If you need the negation NOT, prefix your expression with !.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}

I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}

Use '&&' for AND and use '||' for OR, for example:
bool A;
bool B;
bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR

If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)
If you want logical operation answers are already given.

&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits

many answers above, i will try a different way:
if you are looking for bitwise operations use only one of the marks like:
3 & 1 //==1 - and
4 | 1 //==5 - or

Related

Operator with more than one charecter C#

I need to make an operator with more than one charecter because I want the code to be more readable and more associative.
For example:
public static bool operator !&(bool a, bool b)
{
return ((a == true && b == true) || (a == false && b = false));
}
You can only overload the actual C# operators, it isn't possible to create your own.
The list of overloadable operators is here
C# supports operators() functions only for known operators. This is not possible to create custom operator.
See C# Specification item 14.2.2 Operator overloading:
The overloadable unary operators are:
+ - ! ~ ++ -- true false
The overloadable binary operators are:
+ - * / % & | ^ << >> == != > < >= <=
Only the operators listed above can be overloaded.
Don't do this.
I realize this may not be exactly what you want, and that it is not the same as an operator, but I would recommend you use a method instead, if possible - perhaps an extension method:
public static bool IsBoolEquivalent(this bool a, bool b)
{
return ((a == true && b == true) || (a == false && b = false));
}
Usage:
var myBool = true;
var yourBool = false;
var areTheyEquivalent = myBool.IsBoolEquivalent(yourBool); // returns false

Does combining short-circuiting operators with regular operators change the result of the expression?

I've always believed that using conditional boolean operators (a.k.a. short-circuiting) in stead of regular boolean operators doesn't affect the outcome of an expression.
var result = true | false & false;
has the same result as
var result = true || false && false
Both expressions result in true.
But what if I would mix regular and conditional operators?
var result1 = true || false & false;
var result2 = true | false && false;
What would you expect? I would expect these to still return true. But that isn't the case. Result2 will be false!
I know this is because of the operator precedence. The precedence order is & | && ||. This seems counter intuitive to me. I'd expect an order of & && | ||, in which case all results would be the same (I think).
So I guess my real question isn't if short-circuiting can change the result. The question is why the order of precedence is such that short-circuiting can change the result.
var result2 = true | false && false;
Is calculated as:
var result2 = (true | false) && false;
Because | comes before &&. Now (true | false) evaluates to true, and true && false is false.
As for the why, see this question:
The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...
The precedence of the operators in question seems to be copied directly from the precedence in the C (and C++) programming language.
Now in C, they don't use distinct types for integers and booleans. For example they could write:
if (i | j && x > 0) // cf. the result2 of your question
and this should mean "the integers i and j bitwise or'ed gives something nonzero AND the number x is positive". So | and & are supposed to be mostly used when the operands are thought of as integers (many-bit numbers), and || and && are supposed to be mostly used when the operands are thought of as booleans.
So it might seem natural in C that | binds more strictly than &&.
In C# we have a higher degree of type safety, and there are no conversions from Int32 to Boolean or from Boolean to Int32. Therefore it is no longer possible to "mix" things, and the precedence no longer feels natural.
I guess in theory in C#, one could make the operator
public static bool operator |(bool b, bool c)
have a different precedence than the operator
public static int operator |(int i, int j)
but it wouldn't really make things better?
I think it's very rare that people use boolean non-short-circuit operators like | and short-circuit operators like && in the same expression, but when they do, they should either be very careful about precedence, or just put the parenthesis () there (it will also make the intention more clear).
The & and | operators evaluate both arguments (which could involve calling a method) and then return the result of the and- or or-operation.
The && and || operators only evaluate their arguments to the point where the final result is determined completely.
For example:
true | SomeMethod() and
false & SomeMethod() calls the SomeMethod() function
true || SomeMethod() and
false && SomeMethod() don't.
trueand false in this example could also be variables of course, I simply used constant to make the example easier to understand.

When does overloaded false operator ever gets executed and what is it good for?

I've been searching for actual working code where an overloaded false operator actually gets executed.
This question (What's the false operator in C# good for?) is somewhat the same, but the accepted answer links to an url which is returning a 404 error. I've also looked at How does operator overloading of true and false work? and some other questions.
What I've found in almost all answers is that false only gets executed when you use a short circuited and like x && y. This is evaluated as T.false(x) ? x : T.&(x, y).
Ok, so I have the following code. The struct contains an int and considers itself true if the int is greater than zero.:
public struct MyStruct {
private int _i;
public MyStruct(int i) {
_i = i;
}
public static bool operator true(MyStruct ms) {
return ms._i > 0;
}
public static bool operator false(MyStruct ms) {
return ms._i <= 0;
}
public override string ToString() {
return this._i.ToString();
}
}
Now I would hope the following program will execute and use the overloaded false operator.
class Program {
private static void Main() {
MyStruct b1 = new MyStruct(1); // to be considered true
MyStruct b2 = new MyStruct(-1); // to be considered false
Console.WriteLine(b1 && b2);
Console.WriteLine(b2 && b1);
}
}
However, it does not even compile. It says it cannot apply operator '&&' to operands of type 'MyStruct' and 'MyStruct'.
I know I can implement an overload of the & operator. So let's do that. The & must return a MyStruct, so I can not make it return a bool.
public static MyStruct operator &(MyStruct lhs, MyStruct rhs) {
return new MyStruct(lhs._i & rhs._i);
}
Now the code does compile. Its output is 1 and -1. So the result of b1 && b2 is not the same as that of b2 && b1.
If I debug the code, I see that b1 && b2 first executes the false operator on b1, which returns false. Then it performs the & operator on b1 and b2, which performs a bitwise and on 1 and -1, resulting in 1. So it indeed is first checking if b1 is false.
The second expression, b2 && b1 first executes the false operator on b2, which returns true. Combined with the fact I'm using short circuiting, it doesn't do anything with b1 and just prints out the value of b2.
So yes, the false operator is executed when you use short circuiting. However, it does not execute the true or false operator on the second argument, but instead executes the overloaded & operator on the operands.
When can this ever be useful? Or how can I make my type so that it can check if the two variables both are true?
The contents of the URL you mentioned that was 404 can be found here:
http://web.archive.org/web/20080613013350/http://www.ayende.com/Blog/archive/2006/08/04/7381.aspx
The article that the author is referring to is here:
http://web.archive.org/web/20081120013852/http://steve.emxsoftware.com/NET/Overloading+the++and++operators
To avoid the same issue again, here is the highlights from the article:
A couple months ago I posted about our query API along with an explanation of how it works. Our query API allows us to express our queries using strongly typed C# syntax:
List<Customer> customers = repository.FindAll(Customer.Columns.Age == 20 & Customer.Columns.Name == “foo”);
One of the things I pointed out in my previous posts was that I couldn’t overload the && and || operators directly since the framework doesn’t allow such craziness…at least not directly.
In particular, it is not possible to overload member access, method invocation, or the =, &&, ||, ?:, checked, unchecked, new, typeof, as, and is operators.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_7_2_2.asp
Over the last month I’ve done a little investigation on the topic to see if and how I can get && and || to behave the way I want. This evening I came across the Conditional logical operators page on MSDN which gave me the answer I was looking for:
The operation x && y is evaluated as T.false(x) ? x : T.&(x, y), where T.false(x) is an invocation of the operator false declared in T, and T.&(x, y) is an invocation of the selected operator &. In other words, x is first evaluated and operator false is invoked on the result to determine if x is definitely false. Then, if x is definitely false, the result of the operation is the value previously computed for x. Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x and the value computed for y to produce the result of the operation.
The operation x || y is evaluated as T.true(x) ? x : T.|(x, y), where T.true(x) is an invocation of the operator true declared in T, and T.|(x, y) is an invocation of the selected operator |. In other words, x is first evaluated and operator true is invoked on the result to determine if x is definitely true. Then, if x is definitely true, the result of the operation is the value previously computed for x. Otherwise, y is evaluated, and the selected operator | is invoked on the value previously computed for x and the value computed for y to produce the result of the operation.
Since we already have the & and | operators in place it was simply a matter of overloading the true and false operators to both return false. This results in the & and | operators always being called which in turn results in the two criteria objects being turned into an AndCriteria/OrCriteria!
So now we can express our criteria expressions using the && and || syntax we’re accustomed to.
repository.FindAll(Customer.Columns.Age == 20 && Customer.Columns.Name == “foo”);
repository.FindAll(Customer.Columns.FirstName == “Foo” || Customer.Columns.LastName == “Bar”);
The relevant operator overloads are shown below.
public static bool operator true(Criteria<T> criteria) {
return false;
}
public static bool operator false(Criteria<T> criteria) {
return false;
}
public static Criteria<T> operator &(Criteria<T> lhs, Criteria<T> rhs) {
return new AndCriteria<T>(lhs, rhs);
}
public static Criteria<T> operator |(Criteria<T> lhs, Criteria<T> rhs) {
return new OrCriteria<T>(lhs, rhs);
}
EDIT-
Reading the linked article I was able to get the following output which uses both the true and false operators:
op false on 1
op & on 1 -1
op true on 1
op true on -1
FALSE
op false on -1
op true on -1
FALSE
op true on 1
op true on 1
TRUE
op true on -1
op & on -1 1
op true on -1
op true on 1
TRUE
With the code:
class Program
{
static void Main(string[] args)
{
MyStruct b1 = new MyStruct(1); // to be considered true
MyStruct b2 = new MyStruct(-1); // to be considered false
Console.WriteLine((b1 && b2) ? "TRUE" : "FALSE");
Console.WriteLine((b2 && b1) ? "TRUE" : "FALSE");
Console.WriteLine((b1 || b2) ? "TRUE" : "FALSE");
Console.WriteLine((b2 || b1) ? "TRUE" : "FALSE");
Console.ReadLine();
}
}
public struct MyStruct
{
private int _i;
public MyStruct(int i)
{
_i = i;
}
public static bool operator true(MyStruct ms)
{
Console.WriteLine("op true on {0}", ms);
return ms._i > 0;
}
public static bool operator false(MyStruct ms)
{
Console.WriteLine("op false on {0}", ms);
return ms._i <= 0;
}
public static MyStruct operator &(MyStruct lhs, MyStruct rhs)
{
Console.WriteLine("op & on {0} {1}", lhs, rhs);
if (lhs)
{
return rhs;
}
else
{
return new MyStruct(-1); //-1 is false
}
}
public static MyStruct operator |(MyStruct lhs, MyStruct rhs)
{
Console.WriteLine("op & on {0} {1}", lhs, rhs);
if (lhs)
{
return lhs;
}
else
{
return rhs;
}
}
public override string ToString()
{
return this._i.ToString();
}
}
I'm not sure what you mean when you say the first code can't compile, although it doesnt use the operator true/false, I ran the following code in 2010 express and got the output:
op bool on 1
op bool on -1
False
op bool on -1
False
op bool on -1
op bool on 1
True
op bool on 1
True
Code:
class Program
{
static void Main(string[] args)
{
MyStruct b1 = new MyStruct(1); // to be considered true
MyStruct b2 = new MyStruct(-1); // to be considered false
Console.WriteLine(b1 && b2);
Console.WriteLine(b2 && b1);
Console.WriteLine(b2 || b1);
Console.WriteLine(b1 || b2);
Console.ReadLine();
}
}
public struct MyStruct
{
private int _i;
public MyStruct(int i)
{
_i = i;
}
public static bool operator true(MyStruct ms)
{
Console.WriteLine("op true on {0}", ms);
return ms._i > 0;
}
public static bool operator false(MyStruct ms)
{
Console.WriteLine("op false on {0}", ms);
return ms._i <= 0;
}
public static implicit operator bool(MyStruct ms)
{
Console.WriteLine("op bool on {0}", ms);
return ms._i > 0;
}
public override string ToString()
{
return this._i.ToString();
}
}
Answering your last question: "how can I make my type so that it can check if the two variables both are true?" - just use the & operator. The whole point of && is to short circuit, so that the second argument isn't checked when not necessary.
Check this out:
Console.WriteLine(b1 & b2); // outputs 1
Console.WriteLine(b2 & b1); // outputs 1
You are actually missing one important bit which will allow you to use MyStruct (with & and |) as a boolean - an implicit cast to bool:
public static implicit operator bool(MyStruct ms) {
return ms._i > 0;
}
This allows you to use MyStruct (so also the result of the operators) as such:
if (b1 & b2)
Console.WriteLine("foo");
As the last, possibly most important, note: the problem in your example comes from the fact that you want to do logical operations (check whether 2 instances of MyStruct are true), but your & operator is implemented incorrectly for such a purpose. It works in terms of binary arithmetic, yielding an instance of MyStruct with value 1 when called with arguments MyStruct(1) (true) and MyStruct(-1) (false). So it basically does (true & false) == true. This is why b1 && b2 gives a different result than b2 && b1 in your example. Any further logic based off of this operator will be broken and unpredictable. Behavior of &&, which is implemented in .NET in terms of false and &, confirms this.
EDIT: you want to be able to use MyStruct as a boolean. You implement operators true and false and expect && and || to work in terms of boolean logic. However, you implement & in terms of binary arithmetics (using & on int fields), which makes this implementation of & not compatible with the boolean logic you expect ((1 & -1) == 1, which means (true & false) == false in your interpretation of MyStruct boolean value). Now, consider that && in general is not a logical operator (it doesn't return a bool) - it is a short circuit implemented as T.false(x) ? x : T.&(x, y). Note that it returns MyStruct in your case, which you just interpret as true or false based on the value of its field. The bottom line: you expect && to do a logical test on both operands, but the .NET implementation of && uses your implementation of &, which is not compatible with the boolean logic you expect.
From Microsoft (http://msdn.microsoft.com/en-us/library/6292hy1k.aspx):
Prior to C# 2.0, the true and false operators were used to create user-defined
nullable value types that were compatible with types such as SqlBool. However,
the language now provides built-in support for nullable value types, and
whenever possible you should use those instead of overloading the true and
false operators.
If you're looking to just evaluate your object to a boolean, remove the operator true and operator false overloads and just use the bool overload.
The point of true/false operators is to provide boolean logic semantics without the need for implicit conversion to bool.
If you allow your type to implicitly cast into bool, the true/false operators are no longer needed. But if you want only explicit conversion, or no conversion, but still want to allow your type as a condition in if or while expresssion, you can use true and false operators.

What is the difference between & and && operators in C#

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?
& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:
bool f() {
Console.WriteLine("f called");
return false;
}
bool g() {
Console.WriteLine("g called");
return false;
}
static void Main() {
bool result = f() && g(); // prints "f called"
Console.WriteLine("------");
result = f() & g(); // prints "f called" and "g called"
}
|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.
Of course, user defined types can overload these operators making them do anything they want.
Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/
-&& is short-circuit logical operator
For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped
-& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.
& can be used on either integral types (like int, long etc.) or on bool.
When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.
&& is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.
Example where this matters:
void Action()
{
string name = null;
if(name != null && name.EndsWith("ack"))
{
SomeOtherAction();
}
}
If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.
If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.
One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.
Below example and explanation's may help.
Example:
public static bool Condition1()
{
Console.WriteLine("Condition1 is evaluated.");
return false;
}
public static bool Condition2()
{
Console.WriteLine("Condition2 is evaluated.");
return true;
}
1. Logical Operator
& (ampersand) Logical AND operator
| (pipeline) Logical OR operator
Used for ensuring all operands are evaluated.
if(Condition1() & Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false ,
//thus total expression evaluated to false , but both are operand are evaluated.
}
if (Condition2() | Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true ,
//thus total expression evaluated to true , but both are operand are evaluated.
}
2. Conditional Short Circuit Operator
&& (double ampersand) Conditional AND operator
|| (double pipeline) Conditional OR operator
Used for Skipping the right side operands , Has Side effects so use carefully
if (Condition1() && Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false,
//thus total expression evaluated to false ,
//and here the side effect is that second operand is skipped
//because first operand evaluates to false.
}
if (Condition2() || Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true
//thus remaining operand evaluations can be skipped.
}
Note:
To get better understanding test it in console sample.
References
dotnetmob.com
wikipedia.org
stackoverflow.com
& is a bitwise operator and && is a logical operator that applies to bool operands.
Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.
d=0;
n=10;
// this throws divide by 0 exception because it evaluates the
// mod even though "d != 0" is false
if ( (d != 0) & (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
// This will not evaluate the mod.
if ( (d != 0) && (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
The first one is bitwise and the second one is boolean and.
According to - C# 4.0 The Complete Reference by Herbert Schildt
& - Logical AND Operator
| - Logical OR Operator
&& - Short Circuited AND Operator
|| - Short Circuited OR Operator
A simple example can help understand the phenomena
using System;
class SCops {
static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
d = 0; // now, set d to zero
// Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
// Now, try the same thing without the short-circuit operator.
// This will cause a divide-by-zero error.
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}
Here the & operator checks each and every operand and && checks only the first operand.
As you might notice for 'AND' operations any operand which is false will evaluate the whole expression to false irrespective of any other operands value in the expression.
This short circuited form helps evaluate the first part and is smart enough to know if the second part will be necessary.
Running the program will throw a divide-by-zero error for the last if condition where both the operands are checked for & operator and no exception handling is done to tackle the fact that 'd' can be 0 at any point of time.
The same case applies to '|' in C#.
This is slightly different than C or C++ where '&' and '|' were bitwise AND and OR operators. However C# also applies the bitwise nature of & and | for int variables only.
Hai Friend,
The Operator &&(Logical Operator) is used in conditional statements.
For Instance
if(firstName == 'Tilsan' && lastName == 'Fighter')
{
Response.Write("Welcome Tilsan The Fighter!");
}
the Response.Write statement will run only if both variables firstName and lastName match to their condition.
Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:
bool a, b, c;
a = true;
b = false;
c = a & b;
Response.Write(c); // 'False' will be written to the web page
Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.

What is the difference between the | and || or operators?

I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?
Just like the & and && operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
if(class != null && class.someVar < 20)
If class is null, the if-statement will stop after class != null is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions, and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the | and & operator though: Bitwise Operations.
|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.
condition1 || condition2
Evaluates to true if either condition1 OR condition2 is true.
| is the bitwise OR operator. It's used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:
A = 01010101
B = 10101010
A | B = 11111111
A = 00000001
B = 00010000
A | B = 00010001
A = 10001011
B = 00101100
A | B = 10101111
Hopefully that makes sense.
So to answer the last two questions, I wouldn't say there are any caveats besides "know the difference between the two operators." They're not interchangeable because they do two completely different things.
One is a "bitwise or".
10011b | 01000b => 11011b
The other is a logic or.
true or false => true
Good question. These two operators work the same in PHP and C#.
| is a bitwise OR. It will compare two values by their bits. E.g. 1101 | 0010 = 1111. This is extremely useful when using bit options. E.g. Read = 01 (0X01) Write = 10 (0X02) Read-Write = 11 (0X03). One useful example would be opening files. A simple example would be:
File.Open(FileAccess.Read | FileAccess.Write); //Gives read/write access to the file
|| is a logical OR. This is the way most people think of OR and compares two values based on their truth. E.g. I am going to the store or I will go to the mall. This is the one used most often in code. For example:
if(Name == "Admin" || Name == "Developer") { //allow access } //checks if name equals Admin OR Name equals Developer
PHP Resource: http://us3.php.net/language.operators.bitwise
C# Resources: http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx
http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx
& - (Condition 1 & Condition 2): checks both cases even if first one is false
&& - (Condition 1 && Condition 2): dosen't bother to check second case if case one
is false
&& - operator will make your code run faster, professionally & is rarely used
| - (Condition 1 | Condition 2): checks both cases even if case 1 is true
|| - (Condition 1 || Condition 2): dosen't bother to check second case if first
one is true
|| - operator will make your code run faster, professionally | is rarely used
Simple example in java
public class Driver {
static int x;
static int y;
public static void main(String[] args)
throws Exception {
System.out.println("using double pipe");
if(setX() || setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
System.out.println("using single pipe");
if(setX() | setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
static boolean setX(){
x=5;
return true;
}
static boolean setY(){
y=5;
return true;
}
}
output :
using double pipe
x = 5
y = 0
using single pipe
x = 5
y = 5
By their mathematical definition, OR and AND are binary operators; they verify the LHS and RHS conditions regardless, similarly to | and &.
|| and && alter the properties of the OR and AND operators by stopping them when the LHS condition isn't fulfilled.
The single pipe, |, is one of the bitwise operators.
From Wikipedia:
In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).
For bitwise | and Logicall ||
OR
bitwise & and logicall &&
it means if( a>b | a==0)
in this first left a>b will be evaluated and then a==0 will be evaluated then | operation will be done
but in|| if a>b then if wont check for next RHS
Similarly for & and &&
if(A>0 & B>0)
it will evalue LHS and then RHS then do bitwise & but
in(A>0 && B>0)
if(A>0) is false(LHS) it will directly return false;
The | operator performs a bitwise OR of its two operands (meaning both sides must evaluate to false for it to return false) while the || operator will only evaluate the second operator if it needs to.
http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx
http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx
The singe pipe "|" is the "bitwise" or and should only be used when you know what you're doing. The double pipe "||" is a logical or, and can be used in logical statements, like "x == 0 || x == 1".
Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, "&") will NOT. Also the bitwise or does not perform short circuit evaluation.
A single pipe (|) is the bitwise OR operator.
Two pipes (||) is the logical OR operator.
They are not interchangeable.

Categories

Resources