    Next: Basic Classes Up: Expressions Previous: Isvoid   Contents

Arithmetic and Comparison Operations

Binary Arithmetic

Cool has four binary arithmetic operations: +, -, *, /. The syntax is

```expr1 <op> expr2
```
To evaluate such an expression first expr1 is evaluated and then expr2. The result of the operation is the result of the expression.

The static types of the two sub-expressions must be Int. The static type of the entire arithmetic expression is also Int. Cool has only integer division.

Binary Relations

Cool has three comparison operations: <, <=, =. These comparisons may be applied to subexpressions of any types, subject to the following rules:

• expr1 is an Int if and only if expr2 is an Int
• expr1 is a String if and only if expr2 is a String
• expr1 is a Bool if and only if expr2 is a Bool
• Otherwise, expr1 may be of any type (including SELF_TYPE) and expr2 may be of any (possibly different) type (including SELF_TYPE).
In all cases, the result of the comparison is a Bool. See the type checking rules for more information.

In principle, there is nothing wrong with permitting equality tests between, for example, Bool and Int. However, such a test must always be false and almost certainly indicates some sort of programming error. The Cool type checking rules catch such errors at compile-time instead of waiting until runtime.

On non-basic objects, equality is decided via pointer equality (i.e., whether the memory addresses of the objects are the same). Equality is defined for void: two void values are equal and a void value is never equal to a non-void value. See the operational semantics rules for more informaiton.

Unary Expressions

Finally, there is one unary arithmetic and one unary logical operator.

• The expression ~ <expr> is the integer complement of <expr>. The subexpression <expr> must have static type Int and the entire expression has static type Int.
• The expression not <expr> is the boolean complement of <expr>. The subexpression <expr> must have static type Bool and the entire expression has static type Bool.    Next: Basic Classes Up: Expressions Previous: Isvoid   Contents