OPERATOR PRECEDENCE
Pascal, when determining how to perform calculations, works according to pre-defined rules. These rules may be overridden by the use of parenthesis ().

The priority given to the various operators, from highest to lowest, are

    NOT               Negation
    * / DIV MOD AND
    + - OR
    =  <>  <  <=  >  >=  IN

    The operators are always evaluated left to right


SELF TEST 17: Operator precedence
Given that

  A := 1;      B := 2;      C := 4;

What does X equal after each of the following statements,

  X := A / B / C;               ________________
  X := A + B / C;               ________________
  X := A * B * C;               ________________
  X := A * B - C;               ________________
  X := A + B + C;               ________________
  X := A / B * C;               ________________
  X := A * B / C;               ________________
  X := A + B - C;               ________________

Click here for answer

Parenthesis are used to override the order of precedence. Consider the expression

             A + B
        X = -------
             C + D

becomes in Pascal

        X := ( A + B ) / ( C + D )

and the expression

                   B
        X = A  +  ---  +  D
                   C

becomes in Pascal

        X := A + ( B / C ) + D


SELF TEST 18
Write statements in Pascal which correctly express each of the following mathematical expressions.

             2                                2
 1. Z = X + Y                2.  Z = ( X + Y )

         A + B + E                        B
 3. Z = -----------          4.  Z = A + ---
           D + E                          C

         A + B                              B
 5. Z = -------              6.  Z = A + -------
           C                              D - C


Click here for answer


SELF TEST 19: STATE which of the following statements is wrong and why

     Y := 2X + A
     4 := X - Y
     A := 1 / ( X + ( Y - 2 )
    -J := K + 1
     S := T / * 3
     Z + 1 := A

Click here for answer


Copyright B Brown/P Henry, 1988-1999. All rights reserved.