Precedence rules

The declarations section of yacc input can also contain precedence rules. These describe the precedence and binding of operator tokens.

To understand precedence and binding, it is best to start with an example. In conventional mathematics, multiplication and division are supposed to take place before addition and subtraction (unless parentheses are used to change the order of operation). Multiplication has the same precedence as division, but multiplication and division have higher precedence than addition and subtraction have.

To understand binding, consider the C expressions:
A - B - C
A = B + 8 * 9
To evaluate the first expression, you usually picture the operation proceeding from left to right:
(A - B) - C
To evaluate the second, however, you perform the multiplication first because it has higher precedence than addition:
A = ( B + (8 * 9) )
The multiplication takes place first, the value is added to B, and then the result is assigned to A.
Operations that operate from left to right are called left associative; operations that operate from right to left are called right associative. For example:
a/b/c
can be parsed as:
(a/b)/c		left associative
or:
a/(b/c)		right associative
Inside the declarations section of a yacc grammar, you can specify the precedence and binding of operators with lines of the form:
%left operator operator …
%right operator operator …
Operators that are listed on the same line have the same precedence. For example, you might say:
%left '+' '-'
to indicate that the + and - operations have the same precedence and left associativity. The operators are expressed as single characters inside apostrophes. Literal characters in yacc input are always shown in this format.
When you are listing precedence classes in this way, list them in order of precedence, from lowest to highest. For example:
%left '+' '-'
%left '*' '/'
says that addition and subtraction have a lower precedence than multiplication and division have.

As an example, C generally evaluates expressions from left to right (that is, left associative) while FORTRAN evaluates them from right to left (that is, right associative).