TExcelTAD
Home › Zig › Zig Comptime

Zig Comptime

comptime is Zig's most distinctive feature. It lets ordinary Zig code run during compilation. There is no separate macro language or template language: the same if, for and functions you already know can compute constants, check conditions, unroll loops and even build new types before the program ever starts.

Compile-time constants

Top-level constants are always evaluated at compile time. Inside a function, a comptime block or expression forces compile-time evaluation:

zig · try it yourself
const std = @import("std");

fn fibonacci(n: u32) u64 {
    var a: u64 = 0;
    var b: u64 = 1;
    for (0..n) |_| {
        const next = a + b;
        a = b;
        b = next;
    }
    return a;
}

// computed by the compiler; the program only contains the result
const fib_30 = fibonacci(30);

pub fn main() void {
    const at_runtime = fibonacci(20);
    const at_compile_time = comptime fibonacci(25);
    std.debug.print("{d} {d} {d}\n", .{ at_runtime, at_compile_time, fib_30 });
}
6765 75025 832040

The finished program does not call fibonacci(30) at all — the number 832040 is baked in.

Building lookup tables

A common use is precomputing a table once, at compile time, with a normal loop:

zig · try it yourself
const std = @import("std");

const squares = blk: {
    var table: [10]u32 = undefined;
    for (&table, 0..) |*entry, i| {
        entry.* = @intCast(i * i);
    }
    break :blk table;
};

const is_vowel = blk: {
    var table = [_]bool{false} ** 256;
    for ("aeiouAEIOU") |c| table[c] = true;
    break :blk table;
};

pub fn main() void {
    std.debug.print("squares: {any}\n", .{squares});
    var vowels: u32 = 0;
    for ("Compile Time Magic") |c| {
        if (is_vowel[c]) vowels += 1;
    }
    std.debug.print("vowels: {d}\n", .{vowels});
}
squares: { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 }
vowels: 7

At the top level, var inside a block is fine — it is a compile-time variable that only exists while the compiler evaluates the block.

comptime parameters

A parameter marked comptime must be known at compile time at each call site. The function is then specialised for that value:

zig · try it yourself
const std = @import("std");

fn repeat(comptime text: []const u8, comptime times: usize) *const [text.len * times]u8 {
    return text ** times;
}

fn power(base: u64, comptime exp: u32) u64 {
    var result: u64 = 1;
    inline for (0..exp) |_| result *= base; // unrolled at compile time
    return result;
}

pub fn main() void {
    std.debug.print("{s}\n", .{repeat("ab-", 4)});
    std.debug.print("3^4 = {d}, 2^10 = {d}\n", .{ power(3, 4), power(2, 10) });
}
ab-ab-ab-ab-
3^4 = 81, 2^10 = 1024

Notice the return type of repeat uses text.len * times — types can depend on comptime values.

Types are values

At compile time, types are ordinary values of type type. You can store them in constants, pass them to functions and inspect them with @typeInfo:

zig · try it yourself
const std = @import("std");

const Config = struct {
    port: u16,
    host: []const u8,
    verbose: bool,
};

pub fn main() void {
    const T = u32;
    const x: T = 7;
    std.debug.print("{s} is {d} bytes, x={d}\n", .{ @typeName(T), @sizeOf(T), x });

    const info = @typeInfo(Config).@"struct";
    std.debug.print("Config has {d} fields:\n", .{info.fields.len});
    inline for (info.fields) |field| {
        std.debug.print("  {s}: {s}\n", .{ field.name, @typeName(field.type) });
    }
}
u32 is 4 bytes, x=7
Config has 3 fields:
  port: u16
  host: []const u8
  verbose: bool

inline for unrolls the loop at compile time — needed here because each field has a different type. This kind of reflection is how std.debug.print itself works: it inspects the arguments' types at compile time and generates the right formatting code.

Compile-time checks

@compileError stops compilation with your own message. Combined with comptime conditions, it lets you reject wrong uses before the program runs:

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

fn half(comptime T: type, value: T) T {
    if (@typeInfo(T) != .int) {
        @compileError("half() only works with integers, got " ++ @typeName(T));
    }
    return value / 2;
}

pub fn main() void {
    std.debug.print("{d}\n", .{half(u32, 50)});
    std.debug.print("{d}\n", .{half(f64, 5.0)});
}
text
./example.zig:5:9: error: half() only works with integers, got f64
        @compileError("half() only works with integers, got " ++ @typeName(T));
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

What can and cannot run at compile time

Allowed at comptime Not allowed
arithmetic, loops, recursion reading files or the network
arrays, structs, strings heap allocation with a runtime allocator
calling functions anything depending on runtime input
creating and inspecting types system calls

The compiler also limits the number of backward branches (loop iterations) to catch infinite loops; raise it with @setEvalBranchQuota(n) for heavy computations.

Test yourself

What does comptime before an expression do?

  1. Makes it run faster at runtime
  2. Forces it to be evaluated during compilation
  3. Runs it in a separate thread
  4. Caches the result on disk

What is the type of the value u32 in Zig?

  1. u32
  2. int
  3. type
  4. comptime_int

Why is inline for needed to loop over a struct's fields?

  1. It is faster
  2. Each field has a different type, so the loop must be unrolled at compile time
  3. Normal for loops can't use slices
  4. It isn't needed