-
Notifications
You must be signed in to change notification settings - Fork 764
-
In many popular languages + and - have higher precedence than the bitwise operators (<<, >>, &, ^, | ). So for example 0x1234 & 0x1100 + 0x5678 & 0x0011 is interpreted as 0x1234 & (0x1100 + 0x5678) & 0x0011 and not as (0x1234 & 0x1100) + (0x5678 & 0x0011).
Seems like this started in B/C from using & as 'logical and', then kept this way when && was added, to simplify migration. The relative precedence between == and & was "fixed" in some languages (e.g. Rust and Python), but + still has higher precedence than &.
A few examples of precedence in other languages (taking representatives of the operators):
Rust/Python: + & == &&
C/C++/C#/Java: + == & &&
We think the correct precedence is: & + == &&.
The disadvantage is that if expressions are copied from other languages like Rust/Python, they might be interpreted differently (note that this is anyway the case with == and & in some other languages, like C/C++/C#/Java).
Another note: whenever the expression is too ambiguous for the writer/reader, it is anyway recommended to add parentheses to increase readability.
16 votes ·
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1