🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Comptime Functions

A comptime function call is a call that runs during compilation instead of at run time. Its result is fixed before the program starts, so the program prints a value that was already computed.

Doubling at compile time

Marking a call with comptime runs it during compilation, and the printed result is already fixed.

fn double(n: i32) i32 {
    return n * 2;
}
const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const doubled = comptime double(21);
    try out.print("doubled={d}\n", .{doubled});
}

Factorial in advance

A factorial call marked comptime computes its product before the program runs.

fn factorial(n: u32) u32 {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const f = comptime factorial(5);
    try out.print("fact={d}\n", .{f});
}

A lookup table

A comptime call can build a whole array of powers of two for later lookup.

fn powers() [8]u32 {
    var out: [8]u32 = undefined;
    var i: usize = 0;
    while (i < 8) : (i += 1) {
        out[i] = @as(u32, 1) << @intCast(i);
    }
    return out;
}
const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const table = comptime powers();
    try out.print("p0={d}\n", .{table[0]});
    try out.print("p3={d}\n", .{table[3]});
    try out.print("p7={d}\n", .{table[7]});
}

Example

fn squares() [5]i32 {
    var out: [5]i32 = undefined;
    var i: usize = 0;
    while (i < 5) : (i += 1) {
        const v: i32 = @intCast(i);
        out[i] = v * v;
    }
    return out;
}
const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const table = comptime squares();
    try out.print("s0={d}\n", .{table[0]});
    try out.print("s2={d}\n", .{table[2]});
    try out.print("s4={d}\n", .{table[4]});
}

Key points

  • Comptime call: a comptime call is a call that the compiler runs before the program starts.
  • Comptime block: a comptime block is a block that the compiler runs during compilation.
  • Lookup table: a lookup table is an array built in advance so later code can read a value by index.
  • Power of two: a power of two is a value made by multiplying two by itself a fixed number of times.
  • Compile-time value: a compile-time value is a value that is known when the compiler finishes.
  • Runtime value: a runtime value is a value that is known only while the program runs.

The example builds a table of squares during compilation. Each entry is the square of its index. The program then prints three entries that were already fixed before it started.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does const x = comptime double(21); do?