views:

76

answers:

2

A gotcha I've run into a few times in C-like languages is this:

original | included & ~excluded   // BAD

Due to precedence, this parses as:

original | (included & ~excluded)   // '~excluded' has no effect

Does anyone know what was behind the original design decision of three separate precedence levels for bitwise operators? More importantly, do you agree with the decision, and why?

+6  A: 
Mark Byers
Yes, in logics ∧ also has higher precedence than ∨ for the same reason.
sepp2k
RBerteig
zildjohn01
@zildjohn01: Good point, I have removed the distributivity one. Regarding your question - would I look down on such a language? I'd find it very unintuitive but adding in the extra parentheses rarely makes the code less readable so it wouldn't be a huge problem if I know about it (and I'd probably learn it the hard way - by writing code that doesn't work and debugging it). If a language use illogical (in my opinion) order of precedence then I'd immediately be on my guard, wondering what other "problems" I might run into with that language. It's related to the principle of least astonishment.
Mark Byers
You convinced me with POLA. Sometimes it's hard to draw the line between what changes are OK to make (such as what @RBerteig mentioned), and what changes are too much.
zildjohn01
RBerteig
zildjohn01
+1  A: 

To extend Mark Byers' answer, in boolean algebra (used extensively by electrical engineers to simplify logic circuits to the minimum number of gates and to avoid race conditions), the tradition is that bitwise AND takes precedent over bitwise OR. C was just following this established tradition. See http://en.wikiversity.org/wiki/Boolean_algebra#Combining_Operations :

Just as in ordinary algebra, where multiplication takes priority over addition, AND takes priority (or precedence) over OR.

Jon Rodriguez