Operator Precedence and Associativity: Definition and Relation to Evaluation Order
Introduction
In programming languages, operator precedence and associativity dictate the order in which operators are evaluated. While many programming textbooks provide tables listing these properties, questions arise regarding their interpretation and the source of their definition.
Questions
Answer
Operator Precedence and Associativity Definition
Operator precedence and associativity are defined within the language standard itself. The standard grammar specifies the rules for constructing expressions. By examining these rules, the precedence and associativity of operators can be derived.
For example, in C , the grammar for additive expressions (addition and subtraction) is as follows:
additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression
From this rule, we can deduce that multiplicative expressions (multiplication and division) have higher precedence than additive expressions because they are subrules of additive expressions. Additionally, the left-to-right associativity of the and - operators can be inferred from the rule, which states that an additive expression can be recursively composed of other additive expressions.
Order of Evaluation
It is essential to distinguish between operator precedence and associativity and the order of evaluation. While precedence and associativity determine how operators are grouped, the order of evaluation refers to the sequence in which individual expressions are evaluated. In C , evaluations are not guaranteed to occur strictly according to precedence and associativity.
For example, in the expression f1() f2() * f3(), the * operator has higher precedence than the operator, resulting in the grouping f1() (f2() * f3()). However, the order of evaluation is not defined, meaning that f3(), f1(), or f2() could be evaluated first.
Certain operators, such as the logical OR (||) operator, do impose a sequence on their operand evaluation, allowing for short-circuiting. In x || y, x is always evaluated before y to determine if evaluation of y is necessary.
The above is the detailed content of What do operator precedence and associativity tables actually tell us about expression evaluation in programming languages?. For more information, please follow other related articles on the PHP Chinese website!