In the previous page, we discussed the concept of operator precedence: which operations happen before other operations. For example, multiplication happens before addition, so the expression 5*A+3 means (5*A)+3, rather than 5*(A+3). Frequently one needs the operators in an expression to be evaluated in an order different than that resulting from operator precedence. There are three general approaches that can be made: recasting the expression, assigning intermediate results to temporary variables, and using grouping operators.
Consider what happens if we want to evaluate 5*(A+3). We can rewrite this expression as 5*A+15 — which has the same value as 5*(A+3). This recasts the expression into a form where operator precedence works for us. While recasting a simple expression such as this is a perfectly viable approach, recasting expressions such as sin (πθ/180) is a somewhat more difficult matter.
Another possibility is to assign intermediate results to temporary variables. Evaluating 5*(A+3) is equivalent to evaluating 5*B when B has the value A+3. So the expression 5*(A+3) could be written as an assignment, B=A+3, followed by the expression 5*B. This approach is not only feasible but preferred when the subexpression A+3 is used several times in quick succession. This can occur if we are computing, for example, k*(A+3) for several values of k, but with the same value of A.
Copyright © 2002 Brian Hetrick
Page last updated 13 January 2002.
Building Blocks I
Control Flow II
A First Program
Data Structures I
Building Blocks II
Data Structures II