Integers

Integer Literals

  1. const decimal_int = 98222;
  2. const hex_int = 0xff;
  3. const another_hex_int = 0xFF;
  4. const octal_int = 0o755;
  5. const binary_int = 0b11110000;
  6. // underscores may be placed between two digits as a visual separator
  7. const one_billion = 1_000_000_000;
  8. const binary_mask = 0b1_1111_1111;
  9. const permissions = 0o7_5_5;
  10. const big_address = 0xFF80_0000_0000_0000;

Runtime Integer Values

Integer literals have no size limitation, and if any undefined behavior occurs, the compiler catches it.

However, once an integer value is no longer known at compile-time, it must have a known size, and is vulnerable to undefined behavior.

  1. fn divide(a: i32, b: i32) i32 {
  2. return a / b;
  3. }

In this function, values a and b are known only at runtime, and thus this division operation is vulnerable to both Integer Overflow and Division by Zero.

Operators such as + and - cause undefined behavior on integer overflow. Also available are operations such as +% and -% which are defined to have wrapping arithmetic on all targets.

Zig supports arbitrary bit-width integers, referenced by using an identifier of i or u followed by digits. For example, the identifier i7 refers to a signed 7-bit integer. The maximum allowed bit-width of an integer type is 65535.

See also: