In
programming language theory
Programming language theory (PLT) is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of formal languages known as programming languages. Programming language theory is clo ...
, the associativity of an
operator
Operator may refer to:
Mathematics
* A symbol indicating a mathematical operation
* Logical operator or logical connective in mathematical logic
* Operator (mathematics), mapping that acts on elements of a space to produce elements of another ...
is a property that determines how operators of the same
precedence
Precedence may refer to:
* Message precedence of military communications traffic
* Order of precedence, the ceremonial hierarchy within a nation or state
* Order of operations, in mathematics and computer programming
* Precedence Entertainment, a ...
are grouped in the absence of
parentheses
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
. If an
operand
In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on.
Example
The following arithmetic expression shows an example of operators and operands:
:3 + 6 = 9
In the above exa ...
is both preceded and followed by operators (for example,
^ 3 ^
), and those operators have equal precedence, then the operand may be used as input to two different operations (i.e. the two operations indicated by the two operators). The choice of which operations to apply the operand to, is determined by the associativity of the operators. Operators may be associative (meaning the operations can be grouped arbitrarily), left-associative (meaning the operations are grouped from the left), right-associative (meaning the operations are grouped from the right) or non-associative (meaning operations cannot be chained, often because the output type is incompatible with the input types). The associativity and precedence of an operator is a part of the definition of the programming language; different programming languages may have different associativity and precedence for the same type of operator.
Consider the expression
a ~ b ~ c
. If the operator
~
has left associativity, this expression would be interpreted as
(a ~ b) ~ c
. If the operator has right associativity, the expression would be interpreted as
a ~ (b ~ c)
. If the operator is non-associative, the expression might be a
syntax error, or it might have some special meaning. Some mathematical operators have inherent associativity. For example, subtraction and division, as used in conventional math notation, are inherently left-associative. Addition and multiplication, by contrast, are both left and right associative. (e.g.
(a * b) * c = a * (b * c)
).
Many programming language manuals provide a table of operator precedence and associativity; see, for example,
the table for C and C++.
The concept of notational associativity described here is related to, but different from, the mathematical
associativity
In mathematics, the associative property is a property of some binary operations, which means that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement ...
. An operation that is mathematically associative, by definition requires no notational associativity. (For example, addition has the associative property, therefore it does not have to be either left associative or right associative.) An operation that is not mathematically associative, however, must be notationally left-, right-, or non-associative. (For example, subtraction does not have the associative property, therefore it must have notational associativity.)
Examples
Associativity is only needed when the operators in an expression have the same precedence. Usually
+
and
-
have the same precedence. Consider the expression
7 - 4 + 2
. The result could be either
(7 - 4) + 2 = 5
or
7 - (4 + 2) = 1
. The former result corresponds to the case when
+
and
-
are left-associative, the latter to when
+
and
-
are right-associative.
In order to reflect normal usage,
addition
Addition (usually signified by the plus symbol ) is one of the four basic operations of arithmetic, the other three being subtraction, multiplication and division. The addition of two whole numbers results in the total amount or ''sum'' of ...
,
subtraction
Subtraction is an arithmetic operation that represents the operation of removing objects from a collection. Subtraction is signified by the minus sign, . For example, in the adjacent picture, there are peaches—meaning 5 peaches with 2 taken ...
,
multiplication
Multiplication (often denoted by the cross symbol , by the mid-line dot operator , by juxtaposition, or, on computers, by an asterisk ) is one of the four elementary mathematical operations of arithmetic, with the other ones being ad ...
, and
division
Division or divider may refer to:
Mathematics
*Division (mathematics), the inverse of multiplication
*Division algorithm, a method for computing the result of mathematical division
Military
* Division (military), a formation typically consisting ...
operators are usually left-associative,
while for an
exponentiation
Exponentiation is a mathematical operation, written as , involving two numbers, the '' base'' and the ''exponent'' or ''power'' , and pronounced as " (raised) to the (power of) ". When is a positive integer, exponentiation corresponds to re ...
operator (if present)
[Exponentiation Associativity and Standard Math Notation](_blank)
Codeplea. 23 Aug 2016. Retrieved 20 Sep 2016. and
Knuth's up-arrow operators there is no general agreement. Any
assignment operators are typically right-associative. To prevent cases where operands would be associated with two operators, or no operator at all, operators with the same precedence must have the same associativity.
A detailed example
Consider the expression
5^4^3^2
, in which
^
is taken to be a right-associative exponentiation operator. A parser reading the tokens from left to right would apply the associativity rule to a branch, because of the right-associativity of
^
, in the following way:
# Term
5
is read.
# Nonterminal
^
is read. Node: "
5^
".
# Term
4
is read. Node: "
5^4
".
# Nonterminal
^
is read, triggering the right-associativity rule. Associativity decides node: "
5^(4^
".
# Term
3
is read. Node: "
5^(4^3
".
# Nonterminal
^
is read, triggering the re-application of the right-associativity rule. Node "
5^(4^(3^
".
# Term
2
is read. Node "
5^(4^(3^2
".
# No tokens to read. Apply associativity to produce parse tree "
5^(4^(3^2))
".
This can then be evaluated depth-first, starting at the top node (the first
^
):
# The evaluator walks down the tree, from the first, over the second, to the third
^
expression.
# It evaluates as: 3 = 9. The result replaces the expression branch as the second operand of the second
^
.
# Evaluation continues one level up the
parse tree
A parse tree or parsing tree or derivation tree or concrete syntax tree is an ordered, rooted tree that represents the syntactic structure of a string according to some context-free grammar. The term ''parse tree'' itself is used primarily in comp ...
as: 4 = . Again, the result replaces the expression branch as the second operand of the first
^
.
# Again, the evaluator steps up the tree to the root expression and evaluates as: 5 ≈ . The last remaining branch collapses and the result becomes the overall result, therefore completing overall evaluation.
A left-associative evaluation would have resulted in the parse tree
((5^4)^3)^2
and the completely different result (625) = ≈ .
Right-associativity of assignment operators
In many
imperative programming language
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program co ...
s, the
assignment operator
Assignment, assign or The Assignment may refer to:
* Homework
* Sex assignment
* The process of sending National Basketball Association players to its development league; see
Computing
* Assignment (computer science), a type of modification ...
is defined to be right-associative, and assignment is defined to be an expression (which evaluates to a value), not just a statement. This allows
chained assignment by using the value of one assignment expression as the right operand of the next assignment expression.
In
C, the assignment
a = b
is an expression that evaluates to the same value as the expression
b
converted to the type of
a
, with the
side effect
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
of storing the
R-value of
b
into the
L-value of
a
. Therefore the expression
a = (b = c)
can be interpreted as
b = c; a = c;
. The alternative expression
(a = b) = c
raises an error because
a = b
is not an L-value expression, i.e. it has an R-value but not an L-value where to store the R-value of
c
. The right-associativity of the
=
operator allows expressions such as
a = b = c
to be interpreted as
a = (b = c)
.
In
C++, the assignment
a = b
is an expression that evaluates to the same value as the expression
a
, with the side effect of storing the R-value of
b
into the L-value of
a
. Therefore the expression
a = (b = c)
can still be interpreted as
b = c; a = c;
. And the alternative expression
(a = b) = c
can be interpreted as
a = b; a = c;
instead of raising an error. The right-associativity of the
=
operator allows expressions such as
a = b = c
to be interpreted as
a = (b = c)
.
Non-associative operators
Non-associative operators are operators that have no defined behavior when used in sequence in an expression. In
Prolog
Prolog is a logic programming language associated with artificial intelligence and computational linguistics.
Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily a ...
the infix operator
:-
is non-associative because constructs such as "
a :- b :- c
" constitute syntax errors.
Another possibility is that sequences of certain operators are interpreted in some other way, which cannot be expressed as associativity. This generally means that syntactically, there is a special rule for sequences of these operations, and semantically the behavior is different. A good example is in
Python, which has several such constructs. Since assignments are statements, not operations, the assignment operator does not have a value and is not associative.
Chained assignment is instead implemented by having a grammar rule for sequences of assignments
a = b = c
, which are then assigned left-to-right. Further, combinations of assignment and augmented assignment, like
a = b += c
are not legal in Python, though they are legal C. Another example are comparison operators, such as
>
,
, and
<=
. A chained comparison like
a < b < c
is interpreted as
(a < b) and (b < c)
, not equivalent to either
(a < b) < c
or
a < (b < c)
.
The Python Language Reference
''
/ref>
See also
* Order of operations
In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.
For exam ...
(in arithmetic and algebra)
* Common operator notation (in programming languages)
* Associativity
In mathematics, the associative property is a property of some binary operations, which means that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement ...
(the mathematical property of associativity)
Notes
References
{{reflist
Parsing
Programming language topics
Operators (programming)