Associativity-and-Precedence
Question 1 |
The attributes of three arithmetic operators in some programming language are given below.
Operator Precedence Associativity Arity + High Left Binary − Medium Right Binary ∗ Low Left Binary
The value of the expression 2 – 5 + 1 – 7 * 3 in this language is __________.
9 | |
10 | |
11 | |
12 |
Question 1 Explanation:
+ has highest precedence, so it will be evaluated first.
2 − 5 + 1 − 7 * 3 = 2 − (5 + 1) − 7 * 3 = 2 − 6 − 7 * 3
Now, − has more precedence than *, so sub will be evaluated before * and – has right associative so (6 − 7) will be evaluated first.
2 − 6 − 7 * 3 = (2 − (6 − 7)) * 3 = (2 – (−1)) * 3 = 3 * 3 = 9
2 − 5 + 1 − 7 * 3 = 2 − (5 + 1) − 7 * 3 = 2 − 6 − 7 * 3
Now, − has more precedence than *, so sub will be evaluated before * and – has right associative so (6 − 7) will be evaluated first.
2 − 6 − 7 * 3 = (2 − (6 − 7)) * 3 = (2 – (−1)) * 3 = 3 * 3 = 9