---
title: "Constants"
description: "Declare compile-time values, learn exactly which expressions fold, and use constants in types and patterns."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Constants

`const` names a value the compiler computes before your program runs. A number,
a string or an operator over them folds into each use; a list, a tuple, a struct
or an enum value is placed once in the static pool and read where it lies
([Aggregate constants](#aggregate-constants)). Constants can be top-level, local
to a block, or members of a type. Their names use `SCREAMING_SNAKE_CASE`.

```atoll
const MAX_RETRIES = 5
const PORT: u16 = 8080
const MASK = 0xFF
const SERVICE = "orders"

fn f() void {
    println("${SERVICE} on ${PORT}, retries=${MAX_RETRIES}, mask=${MASK}")
}
```

## Inference and annotation

The annotation is optional when the initializer determines the type.

```atoll
const RETRIES = 5          // int
const LABEL = "worker"     // string
const ENABLED = true       // bool
const RATIO = 0.5          // float

fn f() void {
    println("${RETRIES} ${LABEL} ${ENABLED} ${RATIO}")
}
```

Annotating fixes the type and turns on range checking at the declaration:

```atoll
const FLAG: bool = true
const TEXT: string = "x"
const PRECISE: f64 = 0.5
const INITIAL: char = 'q'
const MARKER: byte = 0x41

fn f() void {
    println("${FLAG} ${TEXT} ${PRECISE} ${INITIAL} ${MARKER}")
}
```

```atoll fail
const TOO_LARGE: u8 = 999

fn f() u8 {
    return TOO_LARGE
}
```

An **unannotated** numeric constant keeps its contextual flexibility, so one
declaration can serve several widths:

```atoll
const CAP = 255

fn f() void {
    byte_cap: u8 = CAP
    wide_cap: u64 = CAP
    println("${byte_cap} ${wide_cap}")
}
```

The use site must still be representable — flexibility is not conversion:

```atoll fail
const CAP = 255

fn f() void {
    too_small: i8 = CAP
    println("${too_small}")
}
```

Once a constant *is* annotated, ordinary type compatibility applies; the
compiler does not reinterpret a declared `u32` as every other width.

## What folds

The constant evaluator handles literals, other constants, and pure scalar
operators. This is the full arithmetic, bitwise, comparison, and logical surface:

```atoll
const A = 10
const B = 3

const SUM = A + B
const DIFF = A - B
const PROD = A * B
const QUOT = A / B
const REM = A % B
const NEG = -A

const SHIFT_L = A << 2
const SHIFT_R = A >> 1
const MASKED = A & B
const MERGED = A | B
const TOGGLED = A ^ B
const INVERTED = ~A

const SMALLER = A < B
const SAME = A == B
const BOTH = SMALLER && SAME
const EITHER = SMALLER || SAME
const FLIPPED = !SMALLER

fn f() int {
    return SUM + DIFF + PROD + QUOT + REM + SHIFT_L + SHIFT_R + MASKED + MERGED + TOGGLED
}
```

Float arithmetic folds too:

```atoll
const PI = 3.14159
const TAU = PI * 2.0

const PRODUCT = "atoll"
const VERSION = "1"

fn f() void {
    println("${PRODUCT}/${VERSION} tau=${TAU}")
}
```

**A constant builds a string by interpolation**, and the string is joined
as the program compiles: the constant is one literal, the text the running
program would have written, and using it costs nothing. A part is another
constant, or an expression of constants: a string, an integer of any width,
a `bool` or a `char`.

```atoll
const HOST = "api.example"
const PORT = 8080
const VERSION = 2
const BASE = "https://${HOST}:${PORT}/v${VERSION}"
const USERS = "${BASE}/users"

fn f() void {
    println(USERS)
}
```

There is no `+` on a `string`, in a constant either: `+` means arithmetic
everywhere, and a string is built by interpolation everywhere — at run time
that is a build into one string, and in a constant it is folded. A float is
not interpolated into a constant, because its text is the running program's
printer's to write; build that string when the program runs.

```atoll fail
const GREETING = "hello" + " world"

fn f() string {
    return GREETING
}
```

Parentheses work as usual, which matters for bit layouts:

```atoll
const LOW_NIBBLE = 0xFF & 0x0F
const HEADER_FLAG = (1 << 4) | 0b0011
const SECONDS_PER_DAY = 60 * 60 * 24

fn f() int {
    return LOW_NIBBLE + HEADER_FLAG + SECONDS_PER_DAY
}
```

## What does not fold

The evaluator is a deliberately small language, not the runtime running inside
the compiler. Each of the following is `ATOLL1019: expression is not
const-evaluable`.

A function call, even of a function that looks pure:

```atoll fail
fn side() int { return 1 }

const X = side()

fn f() int {
    return X
}
```

A method call — including on a constant string:

```atoll fail
const NAME = "atoll"
const LENGTH = NAME.len()

fn f() int {
    return LENGTH
}
```

A branch expression:

```atoll fail
const DEBUG = true
const LEVEL = if DEBUG { 3 } else { 0 }

fn f() int {
    return LEVEL
}
```

And anything that reaches a runtime value:

```atoll fail
fn f(n int) int {
    const DOUBLED = n * 2
    return DOUBLED
}
```

When you need a value computed at run time, use a function.

## Aggregate constants

A top-level constant may hold a list, a tuple, a struct, an enum value or an
`Option`, and the strings and numbers inside them, nested as deep as the types
go. Its parts are constants: literals, other constants, and more aggregates.

```atoll
struct Names {
    months []string
    short  []string
}

enum Mode { Fast, Slow }

const NAMES = [
    Names { months: ["January", "February", "March"], short: ["Jan", "Feb", "Mar"] },
    Names { months: ["janvier", "février", "mars"], short: ["janv.", "févr.", "mars"] }
]

const DEFAULT_MODE = Mode.Fast
const ORIGIN = (0, 0)
const NOTE: string? = Some("draft")

fn month_name(language int, month int) string {
    if Some(names) := NAMES.get(language) {
        return (names.months.get(month) ?? "").clone()
    }
    return ""
}

fn f() int {
    return month_name(1, 2).len() + ORIGIN.0
}
```

**What it costs.** The value is laid out at compile time in the module's
[static pool](#where-a-literal-lives--the-static-pool): each list is a block of
its elements, and each string and inner list is a block of its own that the
element points at. The pool is placed once when the program starts. Naming the
constant, indexing it and reading a field of it read those blocks where they
lie: no block is made, no count is taken or given back, and nothing is copied.
`NAMES[language].months[month]` is two bounds tests and two loads, what the
same read of a list built at run time costs, and less than a table packed into
strings and decoded by hand. A list read alone, `TABLE[i]` in a function a loop
calls, takes the address of its elements from the pool the same way: no frame
is made for it, and the read is the bounds test and a load. Scalar constants
and struct or tuple constants of numbers fold into the code that uses them, as
before.

The pool deduplicates, so a string inside a constant is the same entry as the
same text written as a literal elsewhere. Here the pool ends with three entries
— `"January"`, `"February"` and the list — each at the count the pool holds:

```atoll run=15 pooled=1,1,1
const MONTHS = ["January", "February"]

fn main() int {
    first := "January"
    return first.len() + (MONTHS.get(1) ?? first).len()
}
```

**A constant is never written.** Assigning into one, or calling a method that
changes it, is refused by name:

```atoll refused=ATOLL1059
const NUMBERS = [1, 2, 3]

fn f() void {
    NUMBERS[0] = 5
}
```

```atoll refused=ATOLL2007
const NUMBERS = [1, 2, 3]

fn f() void {
    NUMBERS.push(4)
}
```

**A copy is yours to change.** `mut numbers := NUMBERS` is a view of the pool
with no capacity of its own, so the first write makes the list a block of its
own, as a write to a string literal does. Until then the copy costs nothing:

```atoll run=106
const NUMBERS = [1, 2, 3]

fn main() int {
    mut numbers := NUMBERS
    numbers[0] = 100
    numbers.push(4)
    return (numbers.get(0) ?? 0) + (NUMBERS.get(0) ?? 0) + numbers.len() + NUMBERS.len() - 2
}
```

**Only constants go in.** A call, an operator or anything else computed when
the program runs is refused inside an aggregate constant, where it is written.
An operator over constants is not folded inside one; name its value as a
constant of its own and use that:

```atoll refused=ATOLL1019
const SIZE = 4
const SIZES = [SIZE, SIZE * 2]

fn f() int {
    return SIZES.len()
}
```

```atoll
const SIZE = 4
const DOUBLE = SIZE * 2
const SIZES = [SIZE, DOUBLE]

fn f() int {
    return SIZES.len()
}
```

An aggregate constant is declared at the top level of a file. A local or a
member `const` holds a number or a string:

```atoll fail
fn f() int {
    const NUMBERS = [1, 2, 3]
    return NUMBERS.len()
}
```

A map or a set is a table built when the program runs, and is not a constant.

## Errors the evaluator reports

Division and remainder by zero are caught at compile time, as `ATOLL1095`:

```atoll refused=ATOLL1095
const X = 1 / 0

fn f() int {
    return X
}
```

So is a signed type's least value divided by `-1`, under `/` or `%`, as
`ATOLL1096`: the quotient is one past the type's greatest value, and both
operators trap on the pair when it runs. The division is computed at its
operands' type, or, for untyped operands, at the constant's declared type.
With no type anywhere the arithmetic is exact, so an unannotated
`const R = -128 % -1` is `0`.

```atoll refused=ATOLL1096
const LEAST: i8 = -128
const R = LEAST % -1

fn f() int {
    return R
}
```

Any other division folds as Rust computes it, truncating toward zero:

```atoll
const LEAST: i8 = -128
const HALF = LEAST / 2      // -64
const REST = LEAST % 7      // -2

fn f() int {
    return HALF + REST
}
```

So are dependency cycles, reported once per member:

```atoll fail
const A = B + 1
const B = A + 1

fn f() int {
    return A
}
```

Forward references are fine — the evaluator resolves by declaration identity and
recurses, so declaration order does not matter:

```atoll
const BUFFER_SIZE = HEADER_SIZE + PAYLOAD_SIZE
const HEADER_SIZE = 16
const PAYLOAD_SIZE = 4096

fn f() int {
    return BUFFER_SIZE
}
```

## `SCREAMING_SNAKE_CASE` and reserved words

Query keywords are lexed in uppercase, so a handful of otherwise natural
constant names are unavailable: `LIMIT`, `SELECT`, `FROM`, `WHERE`, `ORDER`,
`AND`, `OR`, and their neighbours.

```atoll fail
const LIMIT = 5

fn f() int {
    return LIMIT
}
```

Pick a qualified name instead — which usually reads better anyway:

```atoll
const PAGE_LIMIT = 5
const SORT_ORDER = 1

fn f() int {
    return PAGE_LIMIT + SORT_ORDER
}
```

Lowercase `limit` and `order` are ordinary identifiers and are unaffected.

## Local constants

A `const` inside a function body is block-scoped. It may reference other visible
constants but not parameters or locals, and it may shadow a top-level constant
of the same name.

```atoll
const TIMEOUT_MS = 1000

fn packet_limit() int {
    const HEADER = 16
    const PAYLOAD = 4096
    return HEADER + PAYLOAD
}

fn adjusted_timeout() int {
    const TIMEOUT_MS = 250        // shadows the top-level constant
    return TIMEOUT_MS
}
```

Use a normal binding when the value depends on runtime state — a local `const`
buys nothing a `let`-style binding does not, except the guarantee that it folded.

## Constants in types and defaults

A constant can size a fixed array and can supply a parameter default:

```atoll
const BUFFER_SLOTS = 4
const DEFAULT_LIMIT = 10

fn take_some(values []int, limit int = DEFAULT_LIMIT) int {
    return values.take(limit).collect().len()
}

fn f() int {
    mut buffer: [BUFFER_SLOTS]int
    buffer[0] = 7
    return take_some([1, 2, 3]) + (buffer.get(0) ?? 0)
}
```

A default names a constant of an imported module the same way, through the
module: `limit int = config.MAX_ROWS`, or `o config.Opts = config.DEFAULTS`
for a constant built of a struct.

## Constants in patterns

A visible constant name used in a pattern matches that constant's *value*
instead of introducing a binding. Fresh names still bind normally; name
resolution decides which reading applies.

```atoll
const QUIT = 0
const HELP = 1

fn dispatch(command int) string {
    return match command {
        QUIT => "quit"
        HELP => "help"
        other => "unknown ${other}"
    }
}

fn f() void {
    println("${dispatch(0)} ${dispatch(1)} ${dispatch(9)}")
}
```

Reach for an enum when the cases form a closed domain. Constant patterns fit
protocol numbers, status codes, masks, and other values that already have a
stable scalar representation.

## Members and associated constants

A struct body may hold a `const`, and a trait may declare an associated constant
that implementations bind. Either is read through the type's name, as `int.MAX`
is:

```atoll run=11
trait Limited {
    const MAX: int
    fn cap(&self) int
}

struct Small {
    size int
    const MIN: int = 3
}

impl Limited for Small {
    const MAX = 8
    fn cap(&self) int => Self.MAX
}

fn main() int {
    s := Small { size: 1 }
    return s.cap() + Small.MIN
}
```

Both fold at compile time, so a read is the literal itself. A trait's
constants — defaults, `Self.MAX`, reading one through a type parameter, and
the refusals — are in [Associated constants](https://docs.atoll.workreef.dev/language/types/traits/#associated-constants).

## Where a literal lives — the static pool

A string literal is not built at run time and is not owned by whoever names it.
It goes in the module's **static pool**, a table of literal values placed once
at compile time, and the pool holds the only reference that matters.

Two consequences follow, and both are observable:

**Identical literals are one entry.** The pool deduplicates, so writing the same
text twice costs one copy, whether the two spellings are in one function or in
different ones.

```atoll run=10 pooled=1
fn main() int {
    a: string = "hello"
    b: string = "hello"
    return a.len() + b.len()
}
```

`pooled=1` says the program ended with **one** pooled entry, at the count the
pool itself holds. Two entries would also answer 10 with a clean heap — the
duplicate is invisible to every other number, because a pooled block is not the
allocator's and never appears in the heap total. This is the one measurement
that sees it.

**A pooled entry is never released to zero.** It is created holding one
reference that belongs to the pool, and nothing gives that back. A pooled
literal is immortal storage for the life of the module, which is why passing one
around costs no retain and no release.

A `const` of string type is the same mechanism reached through a name:

```atoll run=5 pooled=1
const GREETING: string = "hello"

fn main() int {
    return GREETING.len()
}
```

Scalar constants have no pool entry at all — they fold into the instruction that
uses them.

## Constants are not places

A scalar constant has no storage at runtime; its folded value is substituted
into each use. There is nothing for an assignment to reach, and the checker says
so:

```atoll refused=ATOLL1059
const RETRY_BUDGET = 1

fn f() void {
    RETRY_BUDGET = 2
    println("${RETRY_BUDGET}")
}
```

The message is about a *temporary* — `cannot assign into a temporary value` —
because that is what a folded constant is by the time the write is checked. Use
a `mut` binding when a value has to change.

Because folding happens before bodies are lowered, constants have no runtime
initialization order, and they never allocate: an aggregate constant is in the
static pool before the first line of the program runs. Anything needing
allocation, I/O, a host call, or another effect belongs in a function.

## Visibility

Top-level constants take the usual visibility modifiers and participate in
normal imports.

```atoll
pub const DEFAULT_TIMEOUT = 30
private const INTERNAL_TAG = 7
const MODULE_LOCAL = 3

fn budget() int {
    return DEFAULT_TIMEOUT + INTERNAL_TAG + MODULE_LOCAL
}
```

Changing a public constant's value is observable API behavior even when the type
does not change — consumers fold it into control flow, array lengths, and
generated code. Version and review constant changes the same way you would a
signature change.

## Composed example

```atoll
const PROTOCOL_VERSION = 2
const HEADER_BYTES = 8
const MAX_PAYLOAD = 1 << 16
const MAX_FRAME = HEADER_BYTES + MAX_PAYLOAD

const FLAG_COMPRESSED = 0b0000_0001
const FLAG_ENCRYPTED = 0b0000_0010
const FLAG_MASK = FLAG_COMPRESSED | FLAG_ENCRYPTED

error FrameError {
    TooLarge   { size: int }
    BadVersion { got: int }
}

struct Frame {
    version int
    flags   int
    payload []byte
}

fn validate(frame &Frame) int ! FrameError {
    if frame.version != PROTOCOL_VERSION {
        error BadVersion { got: frame.version }
    }
    size := HEADER_BYTES + frame.payload.len()
    if size > MAX_FRAME {
        error TooLarge { size }
    }
    return size
}

fn describe(frame &Frame) string {
    set := frame.flags & FLAG_MASK
    compressed := (set & FLAG_COMPRESSED) != 0
    encrypted := (set & FLAG_ENCRYPTED) != 0
    return "v${frame.version} compressed=${compressed} encrypted=${encrypted}"
}

fn main() void {
    frame := Frame {
        version: PROTOCOL_VERSION
        flags:   FLAG_COMPRESSED
        payload: b"hello"
    }
    println(describe(frame))
    println("size: ${validate(frame).unwrap_or(0)}")
}
```

Source: https://docs.atoll.workreef.dev/language/fundamentals/constants/index.mdx
