3 ms·
> However, the precedence of & vs &&, or & vs ||, etc is a source of problems. Do you have any examples of this? In my experience you almost always want the bi
by Denvercoder9 3y ago
> However, the precedence of & vs &&, or & vs ||, etc is a source of problems.
Do you have any examples of this? In my experience you almost always want the bitwise operators to have a higher precedence than the logical operators, as using the result of logical operators as a bitmask makes little sense. Consider e.g. `A & B && C & D`, which currently is equivalent to `(A & B) && (C & D)`, but with reversed precedence would be equivalent to the almost nonsensical `A & (B && C) & D`.
Now, the precedence of == with respect to & and | is actually problematic (as Ritchie admits as well). Having `A == B | C` interpreted as `(A == B) | C` is almost never desirable. For extra annoyance, the shift operators do have higher precedence than comparison, so `A == B << C` does what you usually want (`A == (B << C)`).
- not2b 3y agoIt usually comes up if the user intended to write && and writes & at one point in an expression, the different precedence can produce an unexpected result. But gcc and clang have warnings for that.
- Denvercoder9 3y agoThe only operators with precedence between & and && are ^ and |, though. In e.g. the expression from the sibling comment, `a & b == c`, writing & or && doesn't make any difference (aside from short-circuiting). I guess it's an issue if you write & instead of && in an expression that also involves a bitwise-OR (or | instead of || in an expression that also involves logical-AND), but that seems quite rare. I expect that reversing the precedence of the bitwise and logical operators would create problems a lot more often.