karthikbalaguru said:
Hi,
Is there a technique to easily remember the order of precedence
of all C operators from high to low priority ?
I think this will save time rather than referring to the chart
for every expression.
Any ideas ?
Two: chunkify; repetition.
To chunkify:
============
There are 15 (too many!) levels of precedence.
The levels fall into groups:
unary, arithmetic, comparison, "boolean", "asymmetric";
Each group is a contiguous band of (two or more) levels
of precedence.
The unary group prefers postfix to prefix: *p++ is *(p++).
It has only two levels.
The arithmetic group has levels for multiplying, adding,
and shifting. The level for shifting is below adding, even
though more sensibly these would be lumped in with multiplying.
Of course multiplying is higher precedence than adding.
The comparison group as all the usual relational operators,
except that == and != have lower precedence than all the
others. I don't know why. This group has two levels.
The "boolean" group has five levels, and only one operator
in each level. The short circuiting ones are at bottom,
the non-short circuiting ones at the top. "And" operators
have higher precedence than the corresponding "or" operators,
so the only "boolean" operator left is bitwise exclusive-or,
which is in between & and |.
The reason the bitwise "boolean" operators have lower
precedence than the relational operators is that origially
C didn't have the short-circuiting (&&,||) versions, so
it made sense to use & and | for boolean combinations.
The "asymmetric" group has three levels:
"if/else" (?
, assignment, "sequence" (,)
Each level has only one operator per level, except of course
there are a zillion subvariations on assignment.
It make sense for assignment to be in the middle of the three
levels, so that: (a) an "if/else" expression, which just has
a value, can be assigned to something without needing parentheses;
and, (b) a single expression can contain several independent
assignments, without needing any parentheses.
Knowing the groups, it's easy to put specific operators in
the right level within each group.
Adding up the groups:
unary: 2 levels
arithmetic: 3 levels
comparison: 2 levels
"boolean": 5 levels
"asymmetric": 3 levels
-----------------------
total 15 levels
For repetition:
===============
Every time you look at an expression and can't remember
which way the precedence works, do this:
1. Write out, by hand and to the best of your memory,
a full precedence table;
2. Look up a full precedence table (several are
available online);
3. Still looking at the precedence table you looked
up, again write out a full precedence table.
Remember in step 1 to include casting, sizeof, and
the prefix unary operators that are hardly ever used.
If you discipline yourself to write parentheses only
when they are necessary because of precedence relationships,
in a very short time you will know the whole table cold.