Arithmetic

There are four arithmetic operators:

  • Addition: +

  • Subtraction: -

  • Multiplication: *

  • Division: /

  • Remainder: %

let a = 1 + 2
// `a` is `3`

The arguments for the operators need to be of the same type. The result is always the same type as the arguments.

The division and remainder operators abort the program when the divisor is zero.

Arithmetic operations on the signed integer types Int8, Int16, Int32, Int64, Int128, Int256, and on the unsigned integer types UInt8, UInt16, UInt32, UInt64, UInt128, UInt256, do not cause values to overflow or underflow.

let a: UInt8 = 255

// Run-time error: The result `256` does not fit in the range of `UInt8`,
// thus a fatal overflow error is raised and the program aborts
//
let b = a + 1
let a: Int8 = 100
let b: Int8 = 100

// Run-time error: The result `10000` does not fit in the range of `Int8`,
// thus a fatal overflow error is raised and the program aborts
//
let c = a * b
let a: Int8 = -128

// Run-time error: The result `128` does not fit in the range of `Int8`,
// thus a fatal overflow error is raised and the program aborts
//
let b = -a

Arithmetic operations on the unsigned integer types Word8, Word16, Word32, Word64 may cause values to overflow or underflow.

For example, the maximum value of an unsigned 8-bit integer is 255 (binary 11111111). Adding 1 results in an overflow, truncation to 8 bits, and the value 0.

//    11111111 = 255
// +         1
// = 100000000 = 0
let a: Word8 = 255
a + 1 // is `0`

Similarly, for the minimum value 0, subtracting 1 wraps around and results in the maximum value 255.

//    00000000
// -         1
// =  11111111 = 255
let b: Word8 = 0
b - 1  // is `255`

Last updated