Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does AND in parenthesis evaluate differently than without?

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?

like image 319
mjamaa wa rwathia Avatar asked Feb 22 '21 03:02

mjamaa wa rwathia


People also ask

How do parentheses affect the precedence rule?

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.

What is the rule for parentheses in math?

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.


1 Answers

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
like image 130
Brian Avatar answered Sep 19 '22 22:09

Brian