Logical OR vs Logical AND: which should be more binding?
I'm writing a small parser, which will have an OR operator and an AND operator. When you see a series of ORs and ANDs, which do you expect will be more bi开发者_开发百科nding? Given the expression a & b | c
, do you expect it to mean (a&b)|c
or a&(b|c)
? Can you give any reason to prefer one over the other?
Do what everyone else does; AND binds tighter than OR (see e.g. C Operator Precedence Table). This is the convention that everyone expects, so adopt the principle of least surprise.
This choice isn't arbitrary. It stems from the fact that AND and OR follow a similar relationship to multiply and add, respectively; see e.g. http://en.wikipedia.org/wiki/Boolean_logic#Other_notations.
Note also that users of your language should be heavily encouraged to use parentheses to make their intentions clear to readers of their code. But that's up to them!
AND and OR in Boolean algebra are equivalent to * and - in regular algebra, so it makes sense that AND binds harder than OR just like * binds harder than +:
A B A*B A&B A+B A|B
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 0 1 1
1 1 1 1 1(>0) 1
If you consider it like you would discrete maths, I'd say PEMDAS leads you to say that the AND is more binding. That's not always the case though.
I recommend you recommending your users to use parentheses wherever there's ambiguity.
Usually & has a precedence over | in many scenarios. But you can restrict expressions to be in a full parenthesis form.
精彩评论