+ 6
What is the difference between logical And(&&) and bitwise And (&) operators?
5 odpowiedzi
+ 11
Logical AND operator:
The logical AND operator (&&) returns the boolean value true if both operands are true and returns falseotherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical AND has left-to-right associativity.
The operands to the logical AND operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions.
The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical AND expression.
The second operand is evaluated only if the first operand evaluates to true (nonzero). This evaluation eliminates needless evaluation of the second operand when the logical AND expression is false.
Bitwise AND operator:
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Both operands to the bitwise AND operator must be of integral types. The usual arithmetic conversions covered in Arithmetic conversions, are applied to the operands.
https://code.sololearn.com/cEk66Ct5lRVe/?ref=app
https://code.sololearn.com/c8rVKN6whKqZ/?ref=app
+ 4
in languages like C++, zero is treated as false and everything else is treated as true. bitwise and will take the binary representation of the arguments and put ones in the places where both arguments have ones. 3&4 in binary would be 0011&0100, so the result would be 0000, false. logical and checks to see if both are true. 3 is not zero, and 4 is not zero, so 3&&4 evaluates to true
+ 4
thank you so much for this wonderful information Abhi Varshini
+ 2
logical and also does something called short circuit evaluation. if the first argument is false, it never checks the second one. this means that 5&&x++ will increase x by one after comparing, but 0&&x++ will not
+ 1
thank you so much forrest