Possible Duplicate:
A clear, layman’s explanation of the difference between | and || in c# ?
What is the difference between comparing with | and || or & and && in C# and Javascript?
Examples:
if(test == test1 | test1 == test2) or if(test == test1 || test1 == test2)
if(test == test1 & test1 == test2) or if(test == test1 && test1 == test2)
The && and || Operators in JavaScript. If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).
Difference between “||” and “|” It's the same as above, in the case of “||” only one statement is executed and if it returns “true” then the other statement will not be executed. But if the first is false then the other will be checked for the value “true”. The reason for this is the way the “or” operator works.
&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true.
in C (and other languages probably) a single |
or &
is a bitwise comparison.
The double ||
or &&
is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"
In practice, since true
is often equivalent to 1
and false
is often equivalent to 0
, the bitwise comparisons can sometimes be valid and return exactly the same result.
There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:
if ( (altitide > 10000) & (knots > 100) )
...
& and | are bitwise operators that can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).
& and | are binary operators while || and && are boolean.
The big difference:
(1 & 2) is 0, false
(1 && 2) is true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With