Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Operators

Arithmetic

Addition (+)

left + right adds two integers and produces their sum.

Subtraction (-)

left - right subtracts the right integer from the left integer and produces their difference.

Multiplication (*)

left * right multiplies two integers and produces their product.

Division (/)

left / right divides the left integer by the right integer and produces their quotient, truncated toward zero. For example, 7 / 2 evaluates to 3, and (0 - 7) / 2 evaluates to -3. A zero divisor causes a division-by-zero error.

Grouping

Multiplication and division share a precedence level above addition and subtraction. Operators at the same precedence group from left to right, so 12 / 3 * 2 groups as (12 / 3) * 2. Parentheses can change the grouping.

print(1 - (2 + 3) + 7 / 2 * 4);

This file prints 8. The term 7 / 2 * 4 groups as (7 / 2) * 4, so the quotient is truncated to 3 before multiplication.

Overflow

If any arithmetic result falls outside the signed 64-bit integer range, evaluation fails with an integer overflow error.

Integer comparisons

OperatorTests whether the left integer is
>Greater than the right integer
>=Greater than or equal to the right integer
<Less than the right integer
<=Less than or equal to the right integer
==Equal to the right integer
!=Different from the right integer

Each comparison returns true or false.

Comparisons bind less tightly than arithmetic, so 2 + 3 == 5 compares (2 + 3) with 5. Write one comparison at a time. A chain such as 1 < 2 < 3 is a syntax error.

Boolean operators

!value flips a boolean. For example, !false evaluates to true. Applying ! to an integer causes a type error.

! binds more tightly than arithmetic and comparisons. To negate a comparison, wrap it in parentheses, as in !(score > 40).

left && right returns false immediately if left is false. left || right returns true immediately if left is true. Otherwise, the operator evaluates and returns right. Every operand that is evaluated must be a boolean.

Comparisons bind more tightly than &&, and && binds more tightly than ||. For example, ready || score >= 40 && score <= 100 checks whether ready is true or both comparisons are true.