C
Charlie Gordon
Ben Bacarisse said:Not that I know, but here are some thing that help me remember:
All the operators that "come after" bind the tightest. If you can't
remember this on it own, just think that a cast, despite being a very
high priority operator, can be used on a function call (or array
element) with no extra brackets: '(char *)function(...)'.
In maths, unary operators usually have high precedence and C follow
this. Thus all the prefix unary operators come next.
Most arithmetic tests don't need extra parentheses because the
relations (==, <, etc) bind more loosely than arithmetic.
Everyone know that * binds more tightly than +, so just remember that
&& and & are the Boolean and bit-wise analogues of multiplication
whereas || and | are the analogues of +. I.e. && binds tighter
than || and & beats |. (Many maths notations use AB or A×B to mean A
and B.)
While this is a good analogy, it may be misleading because & binds less than
+
Remembering that , is the lowest is also easy because , can replace ;
to turn a sequence into an expression (heck, it even looks like a
semicolon). It also mimics the way , behaves in a parameter list
(although of course *that* comma is quite another syntactic entity).
This covers the vast majority of common cases. I also like to
remember that you can assign a conditional ('index += up ? 1 : -1' is
my canonical example), but you can't shift by an arithmetic expression
('x >> (32 - bits)' requires the parentheses).
No, it does not: >> binds less than + and -, but it is certainly a good idea
to use parentheses to make your intent clear for both yourself and the next
person reading the code.
I hope this helps. The basic idea -- remembering what classic cases do
and do not need parentheses -- seems to me more valuable than rote
learning of the table.
Another useful advice is to turn on warnings your compiler might have to
flag common mistakes about operator precedence. gcc has an option for that,
I don't know if other compilers do.