Hi,
Is there a technique to easily remember the order of precedence
of all C operators from high to low priority ?
What you can do is group them into categories. Memorize the precedence
among the categories, and within each category.
First there are the postfix operators, like function calls, array substripting
and postfix increment. They have the same precedence, and clump left to right.
Then the unary operators. They have the same precedence and build up right to
left.
Then comes the math category: add, subtract, multiply, divide, modulus. You
know these from grade school. Modulus % goes with multiplication and division.
Then you have to remember three categories, two of which are subdivided:
- shifting,
- relational,
- inequality
- equality
- logic:
- bitwise
- boolean
Mnemonics: shifting has an arithmetic basis, so it's close to the math
operations. Bitwise logic is also mathematical but because it resembles boolean
logic it is /dragged down/ and settles just above boolean logic. Relational
is in between shifting and logic because, well, relations are connections
that go /between/ things, and relational expressions are the connection
/between/ arithmetic and logic!
Relational less than and greater than tests like >= take precedence over
exact equality tests like != or ==. The way to remember that is:
a > b == b > c. That is, the result of less than or greater than is boolean,
and booleans may be compared using equality, but less than would not be applied
to booleans.
Within logic, you should know that AND has higher precedence than OR, which is
consistent with conventional logical notations. The bitwise exclusive or is
given an intermediate precedence between the two. Mnemonic: it's stronger than
OR (excludes the case when both are true) but weaker than AND (true in cases
where AND isn't). In the truth table, AND has only one truth, XOR has two, and
OR has three. One truth, two truths, three truths -> level 1, level 2, level 3
precedence.
The last three categories are:
- ternary operator
- assignments (plain and compounded with addition, shifting, etc)
- comma operator
You have to come up with something for yourself here.
You should remember that assignments have right to left associativity, and so
does the ternary operator. For assignments this is easy, since the flow of the
data is from right to left.
I think this will save time rather than referring to the chart
for every expression.
So, in summary, subdivide into levels, and conquer the precedence among the
levels and within the levels.
Don't be too clever with precedence. When writing code, clarify it with
parentheses.
Your goal for memorizing precedence should be that you can correctly /read/
even unclear expressions without having to look up precedence; your goal should
not be /writing/ expressions with the minimal possible use of parentheses, so
that others are forced to look up or memorize.
Cheers ...