If we have an expression:
a $ b @ c
$
is a left-associative operator, @
is right-associative.
They have the same precedence.
How is this expression parsed? As (a $ b) @ c
or as a $ (b @ c)
?
Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Explanation: Option 1: Unary Operators have associativity right to left in C++.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
Assignment operators have right-to-left associativity.
This is an excellent question. While Dipstick is correct that in many languages, operator precedences and associativities are defined to avoid such a problem, there are languages in which such a situation may arise.
Haskell is such a language. It allows you to define your own infix operators, and their precedences (integer from 0 to 9) and associativity (left, right, non). It's easy to create the preconditions for the scenario you described:
infixl 5 $$
($$) :: Int -> Int -> Int
a $$ b = a + b
infixr 5 @@
(@@) :: Int -> Int -> Int
a @@ b = a * b
And then the situation itself:
uhoh = 1 $$ 2 @@ 3
This results in this error message:
Precedence parsing error
cannot mix `$$' [infixl 5] and `@@' [infixr 5] in the same infix expression
Of course, Haskell's solution -- aborting with a parse error -- is not the only way to deal with this problem, but it is certainly a reasonable one.
For more information about operator parsing in Haskell, please see section 4.4.2 of the Haskell report.
Operators at the same precedence are all either right associative or all left associative so the problem doesn't arise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With