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
= <> < <= > >= INThe 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; ________________Click here for answer
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; ________________
Parenthesis are used to override the order of precedence. Consider the expression
A + Bbecomes in Pascal
X = -------
C + D
X := ( A + B ) / ( C + D )and the expression
Bbecomes in Pascal
X = A + --- + D
C
X := A + ( B / C ) + D
Self Test on Operator Precedence
2 2
1. Z = X + Y 2. Z = ( X + Y )A + B + E B
3. Z = ----------- 4. Z = A + ---
D + E CA + B B
5. Z = ------- 6. Z = A + -------
C D - C2 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 CZ := (A+B+E) / (D+E); Z := A + (B / C);
A + B B
5. Z = ------- 6. Z = A + -------
C D - CZ := (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;