🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Comptime

Comptime is work the compiler does while building the program, before the program ever runs. Values finished at comptime are baked into the program and can be printed at run time like any other value.

A comptime block finishes before the run

The labeled block adds 4 and 5 while the program is built. main only prints the finished value, 9.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const total: i32 = comptime blk: {
        var sum: i32 = 0;
        sum += 4;
        sum += 5;
        break :blk sum;
    };
    try out.print("{d}\n", .{total});
}

A comptime var is built up by inline for

The inline for loop unrolls over the three items during compilation. Each pass doubles its item into the comptime total.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    comptime var total: i32 = 0;
    inline for ([_]i32{ 1, 2, 3 }) |n| {
        total += n * 2;
    }
    try out.print("{d}\n", .{total});
}

inline for unrolls one pass per item

The loop body is laid out once for each of the three items at compile time. The run prints the three tripled values in order.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    inline for ([_]i32{ 2, 4, 6 }) |n| {
        try out.print("{d}\n", .{n * 3});
    }
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    comptime var squares: i32 = 0;
    inline for ([_]i32{ 1, 2, 3, 4 }) |n| {
        squares += n * n;
    }
    const limit: i32 = comptime blk: {
        var v: i32 = 0;
        v += 5;
        v += 5;
        break :blk v;
    };
    try out.print("squares = {d}\n", .{squares});
    try out.print("limit = {d}\n", .{limit});
    try out.print("combined = {d}\n", .{squares + limit});
}

Key points

  • Comptime: short for compile time, the phase when the compiler builds the program.
  • Comptime block: a block marked comptime runs while the program is being built.
  • comptime var: a variable marked comptime var changes only during compilation.
  • inline for: an inline for loop is unrolled at compile time, so each pass becomes straight-line code.
  • Baked-in values: a value finished at comptime is part of the built program.
  • Run-time printing: normal print code can show a comptime result after the program starts.

In this example, the inline for loop adds the squares of 1, 2, 3, and 4 into the comptime var during compilation, giving 30. The comptime block separately builds the limit value 10. main then prints both finished values and their sum, 40, with ordinary run-time prints.

Note

comptime code cannot read user input, because the program is not running yet.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does inline for do to a loop?