Expert C Programming

(Jeff_L) #1

the order in which these groupings will be evaluated is always undefined. In the expression:


x = f() + g() * h();


The values returned by g() and h() will be grouped together for multiplication, but g and h
might be called in any order. Similarly, f might be called before or after the multiplication,
or even between g and h. All we can know for sure is that the multiplication will occur
before the addition (because the result of the multiplication is one of the operands in the
addition). It would still be poor style to write a program that relied on that knowledge. Most
programming languages don't specify the order of operand evaluation. It is left undefined so
that compiler-writers can take advantage of any quirks in the architecture, or special
knowledge of values that are already in registers.


Pascal avoids all problems in this area by requiring explicit parentheses around expressions that mix
Boolean operators and arithmetic operators. Some authorities recommend that there are only two
precedence levels to remember in C: multiplication and division come before addition and subtraction.
Everything else should be in parentheses. We think that's excellent advice.


Handy Heuristic


What "Associativity" Means


While the precedence of operators can be perplexing, many people are equally puzzled
about the associativity of operators. Operator associativity never seems to be explained very
clearly in the standard C literature. This handy heuristic explains what it is, and when you
need to know about it. The five-cent explanation is that it is a "tie-breaker" for operators
with equal precedence.


Every operator has a level of precedence and a "left" or "right" associativity assigned to it.
The precedence indicates how "tightly" the operands in an unbracketed expression bind. For


example, in the expression a * b + c,since multiplication has a higher precedence


than addition, it will be done first, and the multiplicand will be b, not b + c.


But many operators have the same precedence levels, and this is where associativity comes
in. It is a protocol for explaining the real precedence among all operators that have the same
apparent precedence level. If we have an expression like


int a, b=1, c=2;


a = b = c;

Free download pdf