Skip to content

Operators

Operator is a symbol representing some kind of computation. Computation here refers to broad catoegory, which may include functions, procedures, routines.

For example, plus symbol is an opertor in following expression a + b. a and b called operands.

Unary, Binary, N-ary

Unary - expect only one operand. For example:

  • logical not !a or not a
  • prefix minus -a

Binary - expect only two operands. For example:

  • plus: a + a
  • minus: a - a
  • etc.

I’m not aware of any N-ary operators.

Infix, Prefix, Suffix

There can be different position of operator in relation to operands:

  • Prefix - operator before operands. For example, ++a, -a, !a, + a a (plus in polish notation)…
  • Infix - operator between operands (works only for binary). For example, a + a, a - a
  • Suffix - operator after operands. For example, a++, a a + (plus in reverse polish notation)

Precedence

Precedence is (a set of rules about) the order or priority in which to perform operations in the given expression in the absence of parenthesis.

For example, presedence of multiplication (*) is higher than addition (+), so expression a + b * c is the same as a + (b * c).

If the precedence of some operator is higher it would be always calculated first independently of position, as if there were parenthesis around it.

Associativity

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

There are three possible options:

  • left-associative - operations are grouped from the left to right (a ~ b ~ c = ((a ~ b) ~ c))
  • right-associative - operations are grouped from the right to left (a ~ b ~ c = (a ~ (b ~ c)))
  • non-associative - operations cannot be chained

For example,

  • If subtraction considered left-associative (which is often the case): 3 - 2 - 1 = ((3 - 2) - 1) = 0
  • If subtraction considered righ-associative: 3 - 2 - 1 = (3 - (2 - 1)) = 2

Most common example of left-associative operators are: +, -, *, /. Most common example of right-associative operators are: assignment a = b = c.

Does associativity makes sense for other than binary infix operators? Maybe ternary operator a ? b : c?

Conclusion

As we can see it is quite important to understand precedence and associativity of operators.

There is nothing specific about operators, it is rather tradition of notation which came from mathematics and logic. Instead we can do fine with function-like notation, for example, instead of a + a:

  • plus(a, a) or +(a, a) - in C-like syntax
  • (plus a a) or (+ a a) - in Lisp-like syntax