x = 8 - 4 - 2r = h << 4 + 1str += ((errors == 0) ? "succeeded" : "failed")*utf++ = 0x80 | ucs >> 6 & 0x6fOur original example contains three operators: assignment, addition and multiplication. These operators – indeed all operators – follow a strict precedence which defines the order of evaluation. Since multiplication has higher precedence than addition, which in turn has higher precedence than assigment, the expression is equivalent to:
v = (u + (a * t))
This means the compiler can be trusted with the expression as first presented. No parentheses are required. Good, the language does what we expect.
In Example 1, subtraction binds more tightly (i.e. has higher precedence than) assignment, so the subtractions are performed first. Since all the arithmetic operators associate left to right, the expression is equivalent to:
x = ((8 - 4) - 2)
In Example 2 arithmetic operators bind more tightly than shift operators, so the expression is equivalent to:
r = (h << (4 + 1))
Why did the programmer not write r = h << 5 ? Probably because she really meant:
r = (h << 4) + 1
but bit shifting (like, say, finding the address of something, or subscripting an array) somehow seems closer to the machine and feels as if it ought to be of higher precedence than addition, so the crucial parentheses were missed. (This example is lifted straight from C Traps and Pitfalls, from the section headed: Operators do not always have the precedence you want.)
In Example 3 the parentheses are unneccessary, since the comparison operators bind more tightly than the conditional operator, which in turn binds more tightly than the assignment operators. Do the parentheses help you understand the meaning of this expression? Would you have left them out – and if so, would one of your team-mates have complained?
How should the fourth example be parenthesised, to make its meaning clear? It is equivalent to:
(*(utf++)) = (0x80 | ((ucs >> 6) & 0x6f))
which shows how complicated an expression looks when parentheses are added indiscriminately.
| Copyright © 2004 Thomas Guest |