Any effort put into becoming familiar with precedence tables is likely to pay
off across a range of languages. For example, although C++ introduces several
new operators over C, there are no surprises. The precedence rules remain in
force even if the operators have been overloaded (but that's the subject of
another article). Java operator precedence is almost a subset of C's.
Similarly, scripting languages are generally compatible with C, even where C's
precedence rules are slightly screwy. So, while
Perl introduces lower precedence versions of the
logical operators not, and, and or, it ensures that not binds more
tightly than and which in turn binds more tightly than or. Interestingly,
in Python, where whitespace is syntactically
significant, parentheses can be used not just to indicate order of evaluation,
but also to wrap lengthy expressions over several lines.
According to Koenig, some of C's
peculiarities can be blamed on its heritage:"The precedence of the C logical operators comes about for historical reasons. B, the predecessor of C, had logical operators that corresponded roughly to C's & and | operators. Although
they were defined to act on bits, the compiler would treat them as && and ||
if they were in a conditional context. When the two usages were split apart in
C, it was deemed too dangerous to change the precedence much." |
The more experienced I become as programmer, the fewer parentheses I use. Coming from a mathematical background, it was several months into my first job before I dared use the conditional operator – and when I finally did start using it, I parenthesised all the sub-expressions for safety. Later on in my career, when I first found myself working with the bitwise operators, again, I enclosed sub-expressions with brackets. As my confidence has increased, the brackets have peeled away.
This, though, is simply evolution. Familiarity with the languages you use makes it easier to read expressions without the unnecessary noise of parentheses. Evolving in this way, however, leaves a programmer vulnerable when working on code written by a more experienced team-mate, unless the experienced programmer writes to a lowest common denominator.
Surely it would be better for everyone to program to a highest common denominator. The operator precedence tables are a fundamental part of the language. The rules for using them are simple. Although there are many precedence levels, the operators do group logically. Update your Coding Standards. Prohibit unnecessary parentheses. Brackets off!
| Copyright © 2004 Thomas Guest |