A clear, unprofessional explanation of the difference between | and || in c #?

Ok, so I read about it several times, but I still have to hear a clear, understandable (and catchy) way to find out the difference between:

if (x | y) 

and

 if (x || y) 

.. in the context of C #. Can someone please help me find out this basic truth and how C # specifically treats them differently (because they seem to do the same). If the difference between this part of the code between them does not matter, what should I use as the best by default?

+42
c # bitwise-operators logical-operators
Mar 26 '09 at 5:43
source share
12 answers

|| - logical or operator. See here . It evaluates to true if at least one of the operands is true. You can use it only with boolean operands; it is a mistake to use it with whole operands.

 // Example var one = true || bar(); // result is true; bar() is never called var two = true | bar(); // result is true; bar() is always called 

| is an or operator. See here . If applied to boolean types, it evaluates to true if at least one of the operands is true. If applied to integer types, it calculates a different number. This number has each bit set to 1 if at least one of the operands has a corresponding bit.

 // Example var a = 0x10; var b = 0x01; var c = a | b; // 0x11 == 17 var d = a || b; // Compile error; can't apply || to integers var e = 0x11 == c; // True 

For boolean operands a || b a || b is identical to a | b a | b , with the only exception that b not evaluated if a is true. For this reason || called squirrel cage.

If the difference between a given unit of code between them does not matter, what should I use as the best by default?

As already noted, the difference is not insignificant, so this issue is partially controversial. As for the โ€œbest practice,โ€ there is nobody: you simply use any operator that is correct. In general, people prefer || over | for boolean operands, as you can be sure that it will not create unnecessary side effects.

+83
Mar 26 '09 at 5:50
source share

When used with boolean operands, the operator | is a logical operator just like || but the difference is that the operator || performs a short circuit assessment, and the operator | does not execute.

This means that the second operand is always evaluated using the | operator but using the || operator the second operand is evaluated only if the first operand is false.

The result of the expression is always the same for both operands, but if evaluating the second operand causes something else, it is guaranteed only if you use the | .

Example:

 int a = 0; int b = 0; bool x = (a == 0 || ++b != 0); // here b is still 0, as the "++b != 0" operand was not evaluated bool y = (a == 0 | ++b != 0); // here b is 1, as the "++b != 0" operand was evaluated. 

Short Circuit Assessment || can be used to write a shorter code, since the second operand is evaluated only if the first operand is true. Instead of writing like this:

 if (str == null) { Console.WriteLine("String has to be at least three characters."); } else { if (str.Length < 3) { Console.WriteLine("String has to be at least three characters."); } else{ Console.WriteLine(str); } } 

You can write like this:

 if (str == null || str.Length < 3) { Console.WriteLine("String has to be at least three characters."); } else{ Console.WriteLine(str); } 

The second operand is evaluated only if the first one is false, so you know that you can safely use the string reference in the second operand, since it cannot be null if the second operand is evaluated.

In most cases, you need to use the || , not an operator | . If the first operand is false, there is no need to evaluate the second operand to get the result. In addition, many people (obviously) do not know that you can use the | with boolean operands, so they will be confused when they see that it is used that way in code.

+42
Mar 26 '09 at 7:13
source share

They do not match. One is a bitwise OR, and one is a logical OR.

X || Y is logical or means the same as โ€œX or Yโ€ and applies to bool values. It is used in conditional expressions or tests. X and Y in this case can be replaced by any expression that evaluates to bool. Example:

 if (File.Exists("List.txt") || x > y ) { ..} 

The condition is set to true if one of the two conditions is true. If the first condition is true (if the file exists), then the second condition is not necessary and will not be evaluated.

The only channel (|) is bitwise OR. To find out what this means, you must understand how numbers are stored on your computer. Suppose you have a 16-bit number (Int16) that contains a value of 15. It is actually stored as 0x000F (in hexadecimal format), which is the same as 0000 0000 0000 1111 in binary format. The bitwise OR takes two values โ€‹โ€‹and OR each pair of corresponding bits together, so if the bit is 1 in any quantity, the result is 1. Therefore, if a = 0101 0101 0101 0101 (which is estimated at 0x5555 in the hex) and b = 1010 1010 1010 1010 (which equals 0xAAAA), then a | b = 1111 1111 1111 1111 = 0xFFFF.

You can use bitwise OR (single pipe) in C # to check if one or more specific bits are enabled. You can do this if you have, say, 12 logical or binary values โ€‹โ€‹for testing, and they are all independent. Suppose you have a student database. A set of independent Boolean elements can be as follows: man / woman, home / on campus, current / not current, registered / not registered, etc. Instead of storing a logical field for each of these values, you can only store one bit for each. Male / female can be bit 1. registered / cannot be bit 2.

Then you can use

  if ((bitfield | 0x0001) == 0x0001) { ... } 

as a test, to make sure that the bit is not turned on, except for the student-male bit, which is ignored. BUT? Well, bitwise OR returns 1 for each bit that is included in any number. If the result of the bitwise OR is higher = 0x0001, it means that there are no bits in the bitfield, except maybe the first bit (0x0001), but you cannot say for sure whether the first bit is turned on because it is masked.

There is a corresponding && and &, which is a logical AND and bitwise AND. They have similar behavior.

you can use

  if ((bitfield & 0x0001) == 0x0001) { ... } 

to see if the first bit is included in the bit field.

EDIT: I can't believe I voted for it!

+10
Mar 26 '09 at 5:47
source share

Good answers, but let me add that the right expressions for || are not evaluated if the left expression is true . Keep this in mind when the assessment conditions are: a) the intensity of the work, or b) cause side effects (rarely).

+5
Mar 26 '09 at 6:22
source share

Unlike what most answers say, the meaning is not quite the same as in C ++.

For any two expressions A and B evaluating booleans, A || B and A | B does almost the same thing.

A | B evaluates both A and B, and if one of them evaluates to true, the result will be true.

A || B does almost the same thing, except that it first evaluates A and then evaluates B only if necessary. Since the whole expression is true if either A or B is true, B does not need to be tested at all if A is true. So || faults and skips the evaluation of the second operand when possible, where | the operator will always evaluate both.

The | the operator is often not used, and often this will not change the situation. The only common case I can think of is where it matters:

 if ( foo != null || foo.DoStuff()){ // assuming DoStuff() returns a bool } 

This works because the DoStuff () member function is never called if the left test fails. That is, if foo is NULL, we do not call DoStuff on it. (which will give us a NullReferenceException).

If we used | the statement, DoStuff () will be called whether foo was empty or not.

In integers only | the operator is defined and bitwise OR, as other answers describe. || the operator is not defined for integer types, though, so it's hard to mix them up in C #.

+5
Mar 26 '09 at 6:45
source share

| is a bitwise OR operator (numeric, integer). it works by converting numbers to binary and doing OR for each of the corresponding digits. then again the numbers are already presented in binary form on the computer, so this conversion does not really happen at run time;)

|| is a logical OR operator (logical). it only works with true and false values.

+4
Mar 26 '09 at 5:47
source share

The following will work in C / C ++, because it does not have support for boolean classes in the first class, it processes each expression using the "on" bit on them as true, otherwise false. Actually the following code will not work in C # or Java if x and y are of numeric types.

 if (x | y) 

Thus, the explicit version of the code above:

 if ( (x | y) != 0) 

In C, any expression that has the โ€œonโ€ bit on them leads to true

int i = 8;

if (i) // valid in C, leads to true

int joy = -10;

if (joy) // vaild in C, leads to true

Now back to C #

If x and y are of numeric type, your code is: if (x | y) will not work. Did you try to compile it? This will not work

But for your code, which I could read x and y, it has boolean types, so it will work, so the difference between | and || for boolean types || squirrel cage, | is not. The conclusion is as follows:

  static void Main() { if (x | y) Console.WriteLine("Get"); Console.WriteLine("Yes"); if (x || y) Console.WriteLine("Back"); Console.ReadLine(); } static bool x { get { Console.Write("Hey"); return true; } } static bool y { get { Console.Write("Jude"); return false; } } 

is an:

 HeyJudeGet Yes HeyBack 

Jude will not be printed twice, || is a Boolean operator, many C-derivative logical operators are short-circuited , Boolean expressions are more efficient if they are shorted.

As for layman terms, when you say a short circuit, for example in || (or operator), if the first expression is already true, there is no need to evaluate the second expression. Example: if (answer == 'y' || answer == 'Y'), if the user presses small y, the program does not need to evaluate the second expression (answer == 'Y'). This is a short circuit.

In my code example above, X is true, so Y on || the operator will not be evaluated further, therefore there is no second exit "Jude".

Do not use this code in C #, even if X and Y are of boolean types: if (x | y) . Does not work.

+3
Mar 26 '09 at 7:03
source share

The first bitwise operator works with two numerical values โ€‹โ€‹and leads to the third.

If you have binary variables

 a = 0001001b; b = 1000010b; 

then

 a | b == 1001011b; 

That is, the bit as a result is equal to 1 if it is also equal to 1 in any of the operands. (My example uses 8-bit numbers for clarity)

"double pipe" ||, is a logical OR operator that takes two boolean values โ€‹โ€‹and leads to the third.

+2
Mar 26 '09 at 5:52
source share

Without delving into the details in any way, form or form, here is the real version of the lay person.

Think of "|" as direct "or" in English; think of "|| "like" or else "in English.

Similarly, think of & as "and" in English; think of "& &" as "as well as" in English.

If you read an expression for yourself using these terms, they often make more sense.

+2
Mar 26 '09 at 12:10
source share

We strongly recommend reading this article from Dotnet Mob

For a logical OR operation, if any of its operands evaluates to true, then the whole expression evaluates to true

this is what || The operator does - he skips the remaining estimate when he discovered the truth. Bye | The operator evaluates its complete operands to evaluate the value of the whole expression.

 if(true||Condition1())//it skip Condition1() evaluation { //code inside will be executed } if(true|Condition1())//evaluates Condition1(), but actually no need for that { //code inside will be executed } 

It is better to use a shaky version of the logical operator. Is it OR (||) or AND (& &) Operator.




Consider the following code snippet
 int i=0; if(false||(++i<10))//Now i=1 { //Some Operations } if(true||(++i<10))//i remains same, ie 1 {} 

This effect is called a side effect , which is actually visible on the right side of the expression in short trailing logical operations.

Link: Short Circuit Evaluation in C #

+2
Apr 10 '15 at 14:41
source share

Although this has already been said and answered correctly, I thought that I would add a real layman answer, because a lot of the time that I feel on this site :). Plus I will add an example and vs. && since it is one and the same concept

| vs ||

You tend to use || when you only want to evaluate the second part, if the first part is FALSE. So:

 if (func1() || func2()) {func3();} 

coincides with

 if (func1()) { func3(); } else { if (func2()) {func3();} } 

This may be a way to save processing time. If func2 () took a long time to process, you would not want to do this if func1 () was already true.

& vs &&

In the case of and vs. && is a similar situation when you evaluate only the second part, if the first part is TRUE. For example:

 if (func1() && func2()) {func3();} 

coincides with

 if (func1()) { if (func2()) {func3();}} } 

This may be necessary, since func2 () may depend on func1 (), which is initially true. If you used and and func1 () got the value false, and always ran func2 (), which could cause a runtime error.

Jeff Layman

+1
Mar 26 '09 at 16:02
source share

I had the same question, but I didnโ€™t fully understand the answers until I found this page that explains all this very well and gives really good examples: http://www.codeproject.com/Articles/544990/Understand-how- bitwise-operators-work-Csharp-and-V

0
Oct 06 '15 at 11:03
source share



All Articles