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?
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.
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.
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 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 && .
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
.
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