Chapter 11 Operators

Table of Contents
11.1 Precedence and Associativity
11.2 Arithmetic Operators
11.3 Comparison Operators
11.4 Logical Operators
11.5 Assignment Operators

An operator is a sequence of one or more characters used to produce a value from other language elements. As an example, the + operator, applied to two strings (example: string_1 + string_2) produces their concatenation.

We already said that Cows don't need explicit declaration of variables' type since Cows interpreter extrapolates it from the context. Many operators can be applied to different data types, possibly with different results.

As an example, the sum operator (+) behaves as the standard arithmetic addition when applied to integers, concatenates its operands when applied to strings and, applied to arrays, joins them.

However, this chapter only deals with operators applied to integers and strings; see Chapter 12 for details about arrays operators.

11.1 Precedence and Associativity

Whenever you combine more than one operator in a single expression, precedence and associativity must be considered.

11.1.1 Precedence

The arithmetic expression 5 + 3 * 2 could be solved summing 5 and 3 and multiplying the result by 2 (16) or multiplying 3 by 2 and adding the result to 5 (11). Cows interpreter will choose one way or the other according to operator precedence: operators are ordered by precedence and operators with higher precedence are evaluated first.

As an example, since the * operator has higher precedence than +, Cows will evaluate 5 + 3 * 2 as 11. You can use parenthesis to override this behavior: (5 + 3) * 2 will evaluate to 16.

See Section 11.1.3 for a list of supported operators and their precedence.

11.1.2 Associativity

The expression 16 / 4 / 2 can be solved dividing 16 by 4 first, and then dividing the result by 2, or dividing 4 by 2 first. Result will be 2 or 8 respectively. Operator precedence can't help since we are dealing with multiple instances of the same operator.

Left associativity means that x operator y operator z is evaluated by grouping x with y first while Right associativity means that y is grouped with z first.

Coming back to our example, the / operator has left associativity so 16 / 4 / 2 is evaluated to 2.

You can use parenthesis to override this behavior: 16 / (4 / 2) will evaluate to 8.

See Section 11.1.3 for a list of supported operators and their associativity.

11.1.3 Supported Operators

The list below shows operators supported by G-Cows; they are listed in order of descending precedence. Associativity is indicated by R (Right Associativity) or L (Left Associativity).

  1. R: ++, -, !, - (unary)

  2. L: **

  3. L: *, /, %

  4. L: +, -

  5. L: <, <=, >, >=

  6. L: ==, ~==, !=, ~!=

  7. L: &&

  8. L: ||

  9. R: =, +=, -=, *=, /=, %=, **=

  10. L: $

This manual can be downloaded from http://www.g-cows.org/.