1
$\begingroup$

The concept of precedence and associativity seems straightforward.

The operator precedence is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.

The associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses.

However, from the perspective of programming language theory, I wonder if there's a formal definition for precedence and associativity. With that formal definition, for example, we could argue that if a formal grammar defines the precedence of two operators, or that if a grammar has some property, then the operators in the grammar will have some kind of precedence.

Maybe it is possible to give a formal definition in each programming language case by case, but there's no general one?

$\endgroup$
2
  • 1
    $\begingroup$ Where do those quotes come from? $\endgroup$
    – rici
    Jul 10 at 3:54
  • $\begingroup$ @rici The quotes come from the linked Wikipedia articles. $\endgroup$ Jul 12 at 8:10
2
$\begingroup$

Look at the Swift language where the available operators are not defined in the language, but in the standard library. There are rules that let the compiler distinguish between binary and unary operators. An expression is operands, possibly preceded or followed by unary operators, and separated by binary operators.

That’s decided by the grammar, without any knowledge of the operands. Then we examine the unary operators from inside to outside. An operator on the left/right must be allowed on the left/right. If there is an operator on each side then we apply the one with higher priority. Operators of equal priority are an error.

Next the binary operators. We find the first sequence of operators of highest priority. If these operators have different associativity then we have an error, otherwise the operators are evaluated left to right or right to left. Repeat until all operators are gone.

So precedence and associativity are not part of the grammar, they are attributes of each operator.

And this isn’t about “mathematical expressions”. It’s any expression.

$\endgroup$
1
  • $\begingroup$ Yeah, the precedence and associativity are attributes of each operator, and the general meanings of unary and binary operators seem obvious. But how to generally define these two concepts for ternary operator? $\endgroup$ Jul 12 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.