OPERATOR PRECEDENCE
 

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




Class Exercise on 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 on Operator Precedence
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

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

Z := X + (Y * Y); Z := (X + Y) * (X + Y);

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

Z := (A+B+E) / (D+E); Z := A + (B / C);

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

Z := (A + B) / C; Z := A + ( B / ( D - C ) );

 
STATE which of the following statements is wrong and why,

Y := 2X + A 2 * X + A {missing operator}
4 := X - Y 4 is a constant
A := 1 / ( X + ( Y - 2 ) missing bracket
-J := K + 1 rewrite as j := - ( k + 1);
S := T / * 3 one too many operators
Z + 1 := A rewrite as z:= A - 1;

(c) Shilpa Sayura Foundation 2006-2017