You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
What should be the relative precedence of `+` and `&`?
`&` has higher precedence: a & b + c == (a & b) + c.
75%
`+` has higher precedence: a & b + c == a & (b + c).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
In many popular languages
+
and-
have higher precedence than the bitwise operators (<<
,>>
,&
,^
,|
). So for example0x1234 & 0x1100 + 0x5678 & 0x0011
is interpreted as0x1234 & (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