[ACCEPTED]-Difference between | and || or & and && for comparison-operators
in C (and other languages probably) a single 12
& is a bitwise comparison.
The double 11
&& is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"
In practice, since 10
true is often equivalent to
false is often equivalent 9 to
0, the bitwise comparisons can sometimes 8 be valid and return exactly the same result.
There was once a mission critical 7 software component I ran a static code analyzer 6 on and it pointed out that a bitwise comparison 5 was being used where a logical comparison 4 should have been. Since it was written 3 in C and due to the arrangement of logical 2 comparisons, the software worked just fine 1 with either. Example:
if ( (altitide > 10000) & (knots > 100) ) ...
& and | are bitwise operators that can 11 operate on both integer and Boolean arguments, and 10 && and || are logical operators 9 that can operate only on Boolean arguments. In 8 many languages, if both arguments are Boolean, the 7 key difference is that the logical operators 6 will perform short circuit evaluation and 5 not evaluate the second argument if the 4 first argument is enough to determine the 3 answer (e.g. in the case of &&, if 2 the first argument is false, the second 1 argument is irrelevant).
& and | are binary operators while || and 3 && are boolean.
The big difference:
(1 2 & 2) is 0, false
(1 && 2) is 1 true
| and 6
& are bitwise operators while
&& are logical 5 operators. Usually you'd want to use
|| and 4
&& for if statements and loops and such (i.e. for 3 your examples above). The bitwise operators 2 are for setting and checking bits within 1 bitmasks.
The instance in which you're using a single 7 character (i.e. | or &) is a bitwise 6 comparison of the results. As long as your 5 language evaluates these expressions to 4 a binary value they should return the same 3 results. As a best practice, however, you 2 should use the logical operator as that's 1 what you mean (I think).
The & and | are usually bitwise operations.
Where 6 as && and || are usually logical 5 operations.
For comparison purposes, it's 4 perfectly fine provided that everything 3 returns either a 1 or a 0. Otherwise, it 2 can return false positives. You should avoid 1 this though to prevent hard to read bugs.
More Related questions