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)
This question is related to
c#
comparison
operators
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) )
...
(Assuming C, C++, Java, JavaScript)
|
and &
are bitwise operators while ||
and &&
are logical operators. Usually you'd want to use ||
and &&
for if statements and loops and such (i.e. for your examples above). The bitwise operators are for setting and checking bits within bitmasks.
The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).
The & and | are usually bitwise operations.
Where as && and || are usually logical operations.
For comparison purposes, it's perfectly fine provided that everything returns either a 1 or a 0. Otherwise, it can return false positives. You should avoid this though to prevent hard to read bugs.
& and | are binary operators while || and && are boolean.
The big difference:
(1 & 2) is 0, false
(1 && 2) is true
& 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).
Source: Stackoverflow.com