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.

Finally, we can modify operator precedence by using grouping operators. In almost all computer languages — and in particular in all of JavaScript, Visual Basic for Applications, and the calculator — parentheses are used to group subexpressions which are to be evaluated before operators outside the parentheses are to be applied to them. So the simplest way to evaluate 5*(A+3) is to write exactly that — 5*(A+3). The addition A+3 is evaluated first, then the product 5*(A+3) is evaluated.

Although they are not generally regarded as such, several other contexts effectively perform grouping operations as well. Generally, any language construct that requires a separate expression also isolates that expression from operators outside that construct. In each of the calculator, Visual Basic for Applications, and JavaScript, subscripts are indicated by brackets, as in A[1]. The expression inside the brackets is evaluated without regard to the context surrounding the brackets. Similarly, function parameters, such as in Math.atan2(y,x), are also evaluated without regard to the context surrounding the brackets.

[ Previous page | Top of page | Next page ]

Copyright © 2002 Brian Hetrick

Page last updated 13 January 2002.

Tutorial

Building Blocks I

Expressions

Grouping

Control Flow II

Basic I/O

Algorithms

A First Program

Answers

Modularization

Data Structures I

Recursion

Program Attributes

Building Blocks II

Algorithm Analysis

Structuring

Data Structures II

Abstract Types

Objects

Problem Analysis

Reference Card