When learning
programming languages that use
infix notation, many people get
stuck on using lots of
parentheses. This is partially because they are
inherent in
algebraic notation, but also partially because
operator precedence is not often taught well or at all.
There are two components of operator precedence: binding and associativity. Binding refers to how closely tokens are associated with their context. Associativity defines the direction in which the token is processed.
In certain evil cases, redundant parentheses are still necessary to reduce confusion for those that do not have a full parser in their head. For example, do YOU understand the following?
a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
Despite
inherent difficulties,
C got things mostly right. Its precedence, ordered by
binding (
evaluation), and specifiying the
associativity is as follows:
- () -> .
- left to right
- ! ~ ++ -- - (type) * & sizeof
- right to left
- * / %
- left to right
- + -
- left to right
- << >>
- left to right
- < <= > >=
- left to right
- == !=
- left to right
- &
- left to right
- ^
- left to right
- |
- left to right
- &&
- left to right
- ||
- left to right
- ?:
- right to left
- = += -= etc.
- right to left
- ,
- left to right