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.
Related
This question already has answers here:
Usage of '&' versus '&&'
(4 answers)
Closed 1 year ago.
If I have
if (false && true)
...
can I be sure that every computer/compiler/whatever will do the shortcut that ignores the second condition? In my implementation, the second condition assumes that the first is true, otherwise it will cause a fatal error. For example:
if (Foobar is BoolContainer && Foobar.BoolVar)
...
where BoolContainer is an example class with a boolean property BoolVar.
MSDN states(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators):
The conditional logical AND operator &&, also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true. Otherwise, the result is false. If x evaluates to false, y is not evaluated.
So your assumption is correct. Though you should be careful when you use &:
The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true. Otherwise, the result is false.
The & operator evaluates both operands even if the left-hand operand evaluates to false, so that the operation result is false regardless of the value of the right-hand operand.
You might get unwanted evaluation when you use &.
There is an extreme edge case where && won't necessarily do what you expect. You won't experience this in normal code. ;)
In the below code both booleans will output as True, but if you && them the result will (on some versions of .NET, but not all) not be True (because true2 is an "unusual" true).
Again, this is not something you will ever experience in real life.
namespace MyNamespace
{
using System;
using System.Runtime.InteropServices;
namespace Work
{
[StructLayout(LayoutKind.Explicit)]
public struct HackedBoolean
{
[FieldOffset(0)] public int value;
[FieldOffset(0)] public bool boolean;
public bool GetBool(int seed)
{
value = seed;
return boolean;
}
}
public class MyClassCS
{
public static void Main(string[] args)
{
var hacked = new HackedBoolean();
var true1 = hacked.GetBool(1);
var true2 = hacked.GetBool(2);
Console.WriteLine(true1);
Console.WriteLine(true2);
Console.WriteLine(true1 && true2);
Console.WriteLine(true1 == true2);
Console.ReadLine();
}
}
}
}
Yes it is safe.
If you want both sides to be evaluated you can use & instead of &&.
Otherwise it will skip second condition in this case.
As per the documentation of Conditional Logical ANN operator && on MSDN condition using && operator evaluates to true only when all the conditions evaluates to true.
If any of the conditions evaluates to false, the entire evaluations results as false.
while evaluating the conditions from left to right, next condition is not evaluated if the previous one evaluates to false.
Yes, it is guaranteed by the language specification:
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
In my experience it is a very common idiom for the second part of a short-circuiting conditional expression like this to rely on this behavior.
You might be wondering about why it says "not false" instead of "true". For a bool type, these two are equivalent. At first I thought it was because bool? had a lifted operator to deal with null, but this is not the case. But you can do something similar with a type that overloads the true, false, &, and | operators, and in fact the spec provides the DBBool example struct which does just that.
I was browsing around stack overflow and I encountered this question:
check for duplicate filename when copying files in C#
In this question, this little gem existed:
int i = +1
I have never seen this syntax before. So I opened up the interactive C# window in visual studio:
Microsoft (R) Roslyn C# Compiler version 1.3.4.60902
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> int i = +1;
> i
1
> +1 == 1
true
Is this similar to +=? Is this some new syntax? What is this operator? How is it different than a normal variable declaration?
That's the unary plus operator. From the documentation:
The result of a unary + operation on a numeric type is just the value of the operand.
In most sane contexts1 where you're writing code, it'll be optional (+1 is the same as 1 if we're writing literals).
It mostly exists for symmetry with the unary minus operator.
Most of the time, you'll not write code containing it, but if you're generating code it can be handy to be able to apply a unary operator either way2.
It has no relation to +=.
1Insane code could override this operator for custom types and make it more than a no-op. But I'd love to understand a use case where it makes code more understandable, which should be the main aim of most code.
2E.g. imagine you're chaining a set of operations together and for each additional element, you wish to change the sign of the overall result. This lets you just store an operator and apply it blindly when you finally decide to output a result
For for all signed numeric types the positive-sign is optional. So,
+1 == (+1) == 1
+1.0 == (+1.0) == 1.0
+1L == (+1L) == 1L
+1.0m == (+1.0m) == 1.0m
Do not confuse
int i = +1; // Assigns 1
which is the same as
int i = (+1); // Assigns 1
or simply
int i = 1; // Assigns 1
with
int i += 1; // INCREMENT!
which increments i.
In C# terms there is a binary + operator (the addition operator as in int i = 3 + 4;) and a unary + operator (the plus sign as in int i = +1;).
Think of it the way you think of
int i = -1
and it becomes obvious
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.
Anyway here's my problem I have been modifying a whole C++ program to work in C# and I am pretty much done, I have this If statement in the C++ program.
if(info[i].location & 0x8 ||
info[i].location & 0x100||
info[i].location & 0x200)
{
//do work
}
else
{
return
}
And of course when I do this in C# it gives me a "Operator '||' cannot be applied to operands of type 'int' and 'int'" error.
Any clue on what my problem is, Im guessing that C# has got a way of doing this as I am fairly unfamiliar with these old C operators.
Why it fails
Fundamentally it's the same difference as this:
if (someInteger) // C or C++
vs
if (someInteger != 0) // C#
Basically C# is a lot stricter when it comes to logical operators and conditions - it forces you to have use something which is either bool or convertible to bool.
As an aside, that's also why in C# this isn't just a warning, but a full-blown error:
int x = ...;
if (x = 10) // Whoops - meant to be == but it's actually an assignment
If you see comparisons this way round:
if (10 == x)
That's usually developers trying to avoid typos like the above - but it's not needed in C# unless you're really comparing against constant bool values.
Fixing the problem
I suspect you just need:
if (((info[i].location & 0x8) != 0)) ||
((info[i].location & 0x100) != 0)) ||
((info[i].location & 0x200) != 0)))
It's possible that you don't need all of those brackets... but another alternative is just to use one test:
if ((info[i].location & 0x308) != 0)
After all, you're just testing whether any of those three bits are set...
You should also consider using a flags-based enum:
[Flags]
public enum LocationTypes
{
Foo = 1 << 3; // The original 0x8
Bar = 1 << 8; // The original 0x100
Baz = 1 << 9; // The original 0x200
}
Then you could use:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if ((info[i].location) & mask != 0)
Or using Unconstrained Melody:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if (info[i].location.HasAny(mask))
It's pretty much exactly what it says: in C#, || is a logical-only operator and so cannot work on int. You can replace || with | (the bitwise-or which works on ints), but then the entire expression will need to be converted to boolean by comparing it to zero, because in C# the if-statements require a boolean.
Alternatively, you can replace info[i].location & 0x8 with (info[i].location & 0x8 != 0).
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