Skip to content

Arithmetic#

CEL supports standard arithmetic operations on numeric types.

Negation#

The unary - operator negates a numeric value.

-3.14
// result: -3.14 (double)
// input: x = 100
-x
// result: -100 (int)

Negation is not defined for unsigned integers.

-1u
// error: found no matching overload for '-_' applied to '(uint)'

Basic operations#

Addition, subtraction, multiplication, and division work on numeric types.

1 + 2
// result: 3 (int)
10u - 4u
// result: 6 (uint)
3.0 * 4.0
// result: 12 (double)

Integer division truncates toward zero.

15 / 4
// result: 3 (int)
-15 / 4
// result: -3 (int)

Modulo#

The % operator returns the remainder after division. The result has the same sign as the dividend.

17 % 5
// result: 2 (int)
-17 % 5
// result: -2 (int)
17 % -5
// result: 2 (int)

Operator precedence#

Multiplication, division, and modulo have higher precedence than addition and subtraction.

1 + 2 * 3
// result: 7 (int)
(1 + 2) * 3
// result: 9 (int)

Division by zero#

Integer and unsigned integer division by zero produces a runtime error.

1 / 0
// error: division by zero
1 % 0
// error: modulus by zero

Double division by zero produces special values.

1.0 / 0.0
// result: +Inf (double)
-1.0 / 0.0
// result: -Inf (double)
0.0 / 0.0
// result: NaN (double)

Overflow#

Integer operations that exceed the 64-bit range produce a runtime error.

9223372036854775807 + 1
// error: integer overflow
-9223372036854775808 - 1
// error: integer overflow

Unsigned integer overflow also produces a runtime error.

0u - 1u
// error: unsigned integer overflow

Mixed types#

Numeric types cannot be mixed directly.

1 + 2u
// error: found no matching overload for '_+_'

Convert explicitly into matching types.

1 + int(2u)
// result: 3 (int)

See also#