Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between logical and conditional AND, OR in C#? [duplicate]

Possible Duplicate:
What is the diffference between the | and || or operators?

Logical AND and OR:

(x & y) (x | y) 

Conditional AND and OR:

(x && y) (x || y) 

I've only known about conditional operands up to this point. I know what it does and how to apply it in if-statements. But what is the purpose of logical operands?

like image 834
Sahat Yalkabov Avatar asked Jun 30 '10 23:06

Sahat Yalkabov


People also ask

What is the difference between logical AND conditional and?

Unlike the Boolean logical operators "&" and "|," which always evaluate both the operands, conditional logical operators execute the second operand only if necessary. As a result, conditional logical operators are faster than Boolean logical operators and are often preferred.

What is the difference between the logic operators and and OR?

The bitwise OR operator sets the bit value whereas the logical OR operator sets true or 1 if either one of the conditions/bit value is 1 else it sets false or 0.

What is the difference between logical AND && and logical or?

It is a binary AND Operator and copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100. Whereas && is a logical AND operator and operates on boolean operands. If both the operands are true, then the condition becomes true otherwise it is false.

Is it && or & in C?

& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & . if you want to use to phrase and you want to treat them logically you can use && .


1 Answers

I prefer to think of it as "bitwise vs. conditional" rather than "logical vs conditional" since the general concept of "logical" applies in both cases.

x & y    // bitwise AND, 0101 & 0011 = 0001 x | y    // bitwise OR,  0101 | 0011 = 0111  x && y   // true if both x and y are true x || y   // true if either x or y are true 

Edit

By popular demand, I should also mention that the arguments are evaluated differently. In the conditional version, if the result of the entire operation can be determined by the first argument, the second argument is not evaluated. This is called short-circuit evaluation. Bitwise operations have to evaluate both sides in order to compute the final value.

For example:

x.foo() && y.bar() 

This will only call y.bar() if x.foo() evaluates to true. Conversely,

x.foo() || y.bar() 

will only call y.bar() if x.foo() evaluates to false.

like image 159
Cogwheel Avatar answered Sep 27 '22 21:09

Cogwheel