In C++, 4&1 == 0
, and 1&1 == 1
. However, 4&1 != 1&1
evaluates to 0
, instead of 1
, yet (4&1) != (1&1)
evaluates to 1
as expected. Why is this?
Expression evaluation is from left to right; parentheses and operator precedence modify this: When parentheses are encountered (other than those that identify function calls) the entire subexpression between the parentheses is evaluated immediately when the term is required.
When a math problem has parentheses, the problem is solved first by calculating the operation inside of the parentheses. If there is no operation symbol or exponent inside of the parentheses, then the parentheses indicate multiplication.
The relational operator !=
has a higher precedence than bitwise AND &
.
Thus the expression
4 & 1 != 1 & 1
will be parsed as
4 & (1 != 1) & 1
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