Next: Notes Up: Arithmetic expressions Previous: Arithmetic expressions

Operator precedence

The basic arithmetic operators are:

For a more complicated expression, such as

   a= b * 2 + c - 64 / d;

we need to know the operator precedence used by C to evaluate the expression. This table gives the order:

and they group left to right.

Strictly, the order is not defined within associative and commutative operations and hence

        a + (b + c)

might be evaluated as

        (a + b) + c

In other words, not even the brackets will force the order of evaluation within the same precedence level. (see the Notes on side-effects, at the end, to see why this might matter.) However, brackets can be used to change precedence because brackets have higher precedence than any of these operators:

   a= b * ( 2 +  (c - 64 / d) );

Convince yourselves that, if b= 10; c= 20; d=2; then the two forms give the values a= 8; a= -100 respectively.

The earlier expression is equivalent to:

   a= (b * 2) + c - (64 / d);

and it is perfectly correct practice, to use brackets to show what you mean. However, it is also good style to use spacing to emphasise the binding of the operators, although this is not a substitute for brackets to force a particular interpretation.

   a= b*2  +  c  -  64/d;



Next: Notes Up: Arithmetic expressions Previous: Arithmetic expressions


maspjw@
Tue Sep 27 15:29:34 BST 1994