Concepts of Programming Languages

(Sean Pound) #1
7.2 Arithmetic Expressions 321

The precedences of the arithmetic operators of Ruby and the C-based
languages are as follows:

The ** operator is exponentiation. The % operator takes two integer
operands and yields the remainder of the first after division by the second.^1 The
++ and -- operators of the C-based languages are described in Section 7.7.4.
APL is odd among languages because it has a single level of precedence, as
illustrated in the next section.
Precedence accounts for only some of the rules for the order of operator
evaluation; associativity rules also affect it.

7.2.1.2 Associativity
Consider the following expression:

a - b + c - d

If the addition and subtraction operators have the same level of precedence, as
they do in programming languages, the precedence rules say nothing about the
order of evaluation of the operators in this expression.
When an expression contains two adjacent^2 occurrences of operators with
the same level of precedence, the question of which operator is evaluated first
is answered by the associativity rules of the language. An operator can have
either left or right associativity, meaning that when there are two adjacent
operators with the same precedence, the left operator is evaluated first or the
right operator is evaluated first, respectively.
Associativity in common languages is left to right, except that the expo-
nentiation operator (when provided) sometimes associates right to left. In the
Java expression

a - b + c

the left operator is evaluated first.


  1. In versions of C before C99, the % operator was implementation dependent in some situa-
    tions, because division was also implementation dependent.

  2. We call operators “adjacent” if they are separated by a single operand.


Ruby C-Based Languages
Highest ** postfix ++, --
unary +, - prefix ++, --, unary +, -
*, /, %*, /, %
Lowest binary +, - binary +, -
Free download pdf