Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Comptime and Generics

Comptime Basics

Learn Zig comptime: running ordinary code at compile time, comptime parameters and variables, comptime-known sizes, compile errors, inline loops and limits, with examples.

Most languages have a separate mini-language for compile-time work: C has a preprocessor with macros, C++ has templates and constexpr, Rust has macro_rules! and const functions. Zig has one idea instead: comptime. You write normal Zig code and ask the compiler to run it while compiling. Generics, conditional compilation, lookup tables and even custom type construction all come out of that single feature.

Evaluating code at compile time

Put comptime in front of an expression and the compiler evaluates it during compilation. The result is a constant baked into the program.

ZIG
const std = @import("std");

fn fib(n: u32) u64 {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
}

pub fn main() void {
    const x = comptime fib(20); // computed by the compiler
    std.debug.print("fib(20) = {d}\n", .{x}); // fib(20) = 6765
}

fib is an ordinary function: the same code could run at runtime. What changed is only when. The binary contains the number 6765, not a call.

Many things are comptime-known automatically. Top-level const declarations and numeric literals are. The compiler runs code at compile time on its own whenever the language requires a comptime-known value, for example an array length:

ZIG
const size = fib(10);          // 55, evaluated at compile time
var table: [size]u8 = undefined; // array lengths must be comptime-known

If you try var n: usize = readNumber(); var a: [n]u8 = undefined; the compiler reports that n is not comptime-known. Use an allocator for runtime sizes.

comptime parameters

A parameter marked comptime must receive a value known at compile time. The function is then compiled separately for each distinct value, like a template:

ZIG
fn repeat(comptime n: usize, text: []const u8, out: *[n * 3]u8) void {
    _ = text;
    @memset(out, 'z');
}

The most important use is comptime T: type, a type passed as a value. That is how generics work (see Generic functions with comptime). Types are first-class comptime values: you can store them in consts, pass them to functions and return them from functions.

comptime variables and blocks

Inside a function you can declare a comptime var and mutate it, as long as everything that touches it is comptime-known:

ZIG
fn sumTo(comptime n: u32) u32 {
    comptime var total: u32 = 0;
    comptime var i: u32 = 1;
    inline while (i <= n) : (i += 1) {
        total += i;
    }
    return total;
}

A comptime { ... } block executes its statements during compilation. It is a good place for compile-time assertions that fail the build instead of a program:

ZIG
comptime {
    std.debug.assert(@sizeOf(u32) == 4);
}

inline loops

A normal for or while runs at runtime. An inline for (or inline while) is unrolled by the compiler: the body is repeated once per element, and inside it each element can be comptime-known. That is what lets you loop over the fields of a struct (types differ per field) or over a tuple of mixed types:

ZIG
const pair = .{ 1, "two", 3.0 }; // a tuple of three different types
inline for (pair) |item| {
    std.debug.print("{any}\n", .{@TypeOf(item)}); // a different type each time
}

An ordinary for cannot do that, because one loop body cannot have three different types for item.

Compile errors you write yourself

@compileError("message") stops compilation with your own message, but only if that code path is actually compiled. Combined with comptime conditions it gives precise errors to library users:

ZIG
fn onlyIntegers(comptime T: type, x: T) T {
    if (@typeInfo(T) != .int and @typeInfo(T) != .comptime_int) {
        @compileError("onlyIntegers expects an integer type, got " ++ @typeName(T));
    }
    return x * 2;
}

Calling onlyIntegers(f32, 1.5) fails to build with that message, at the call site, not at runtime.

Conditional compilation without a preprocessor

Because if on a comptime-known condition only compiles the taken branch, platform code is just if:

ZIG
const builtin = @import("builtin");

pub fn pathSeparator() u8 {
    if (builtin.os.tag == .windows) return '\\' else return '/';
}

The untaken branch is not compiled at all, so it may even reference functions that do not exist on this OS.

What comptime cannot do

  • No I/O, no network, no system calls, no heap allocation (comptime has no allocator by default).
  • No reading runtime values. A value is comptime-known only if everything it depends on is.
  • Limited work: the compiler caps backward branches (loops and recursion) at a default of 1000 and reports an error if you exceed it. Raise it with @setEvalBranchQuota(100_000) inside the function that needs it.
  • Slower builds: heavy comptime work is paid for at every compile.
flowchart LR
  S["source code"] --> C["compiler"]
  C -->|"comptime-known?"| E["evaluate now<br/>(constant in binary)"]
  C -->|"runtime value?"| R["emit machine code"]

Caption: the compiler decides per expression whether to compute now or generate code.

A runnable stand-in

Go has no comptime, but we can imitate the "build a lookup table once, up front" use. In Zig the table below would be computed during compilation and baked into the binary; in Go it is computed at program start, with the same result.

Go Stand-in: a precomputed table (Go, runtime instead of compile time)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Expecting a runtime variable to work where a comptime value is needed (array length, comptime parameter).
  • Forgetting inline and wondering why a loop over a tuple will not compile.
  • Doing huge computations at comptime and then hitting the branch quota or long build times.
  • Using @compileError in code that is always compiled, so the whole build fails.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does comptime do?

    comptime evaluates ordinary Zig code at compile time and bakes the result into the program.
  2. 2. Which needs a comptime-known value?

    Array lengths are part of the type, so they must be known while compiling.
  3. 3. Why is inline for needed to loop over a tuple of mixed types?

    A single compiled loop body cannot have a different type for the capture on each pass; unrolling gives each iteration its own types.
  4. 4. What can comptime code NOT do by default?

    Compile-time execution has no I/O and no allocator by default.

Summary

  • comptime runs normal Zig code during compilation; one feature replaces macros, templates and preprocessor conditions.
  • Array lengths and comptime parameters need comptime-known values.
  • inline for unrolls loops so each iteration can have different types.
  • @compileError gives readable build errors; the evaluation branch quota can be raised with @setEvalBranchQuota.

Next: Generic functions with comptime