Zig Comptime
Say your program needs a table: the squares of 0 to 9, or a list of which bytes are vowels. You could type it out by hand, fill it in when the program starts, or (in C) write a macro or a script that generates the code. Zig gives you a simpler option: write a normal Zig loop, and let the compiler run it while it builds your program. That’s comptime, short for “compile time”. It’s the same Zig you already know, just running earlier, and it’s the idea behind Zig’s generics, reflection and much of the standard library. This page shows what it is and how to use it; the next pages build on it.
Two moments: compile time and run time
Section titled “Two moments: compile time and run time”Every value in a Zig program is known at one of two moments:
- Compile time: while
zigis building your program. A number literal like5, or aconstmade only from such values, is known here. - Run time: while your program is running. A
var, user input, a file’s contents: those only exist once the program runs.
Put the comptime keyword in front of an expression, and Zig must work it out while compiling:
const std = @import("std");
fn fibonacci(n: u32) u32 { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2);}
pub fn main() void { const at_compile_time = comptime fibonacci(12);
var n: u32 = 12; _ = &n; const at_run_time = fibonacci(n);
std.debug.print("compile time: {d}\n", .{at_compile_time}); std.debug.print("run time: {d}\n", .{at_run_time});}Output:
compile time: 144run time: 144fibonacci is an ordinary function, and here it runs twice. The first call runs inside the compiler: the finished program doesn’t call fibonacci(12) at all, it just contains the number 144. The second call happens when you run the program, because n is a var (the _ = &n; line tells Zig “yes, I know I never change it”). You didn’t write a special version of the function for compile time. Any Zig function can run at either moment, as long as it only uses what that moment has.
If you ask for compile time but hand it a run-time value, Zig refuses:
fn square(x: u32) u32 { return x * x;}
pub fn main() void { var input: u32 = 7; _ = &input; const result = comptime square(input); _ = result;}main.zig:8:36: error: unable to resolve comptime value const result = comptime square(input); ^~~~~main.zig:8:20: note: 'comptime' keyword forces comptime evaluation const result = comptime square(input); ^~~~~~~~~~~~~~~~~~~~~~“Unable to resolve comptime value” is the error you’ll see most in this section. It always means the same thing: Zig needed to know something while compiling, and it won’t be known until the program runs.
Building a table while compiling
Section titled “Building a table while compiling”Here’s the vowel table from the intro. Code at the top level of a file (outside any function) is always run at compile time, so you don’t even need the comptime keyword:
const std = @import("std");
const is_vowel = blk: { var table: [256]bool = @splat(false); for ("aeiouAEIOU") |c| table[c] = true; break :blk table;};
pub fn main() void { const word = "Comptime is fun"; var count: usize = 0; for (word) |c| { if (is_vowel[c]) count += 1; } std.debug.print("\"{s}\" has {d} vowels\n", .{ word, count });}Output:
"Comptime is fun" has 5 vowelsThe blk: { ... break :blk table; } part is a labeled block (see Zig Blocks): it runs some statements and hands back a value. @splat(false) fills all 256 slots with false, then the loop flips the vowels to true. All of that happens while compiling. Your program starts with the finished 256-entry table already in it, and looking up is_vowel[c] is a single array read.
comptime parameters
Section titled “comptime parameters”A function parameter can be marked comptime. Then every caller must pass a value known at compile time, and inside the function you can use it where Zig needs a compile-time value, like the length of an array:
const std = @import("std");
fn filled(comptime n: usize, char: u8) [n]u8 { var result: [n]u8 = undefined; @memset(&result, char); return result;}
pub fn main() void { const line = filled(10, '-'); const stars = filled(3, '*'); std.debug.print("{s}\n{s}\n", .{ &line, &stars }); std.debug.print("{d} and {d} bytes\n", .{ line.len, stars.len });}Output:
----------***10 and 3 bytesAn array’s length is part of its type (see Zig Arrays), so [n]u8 only makes sense if n is known while compiling. The comptime n parameter makes that a promise. char is a normal parameter, so it can be anything, even a run-time value.
Zig makes a separate copy of filled for each different n: one that returns [10]u8 and one that returns [3]u8. Try to pass a run-time number and you get the familiar error, plus a note pointing at the parameter:
fn filled(comptime n: usize, char: u8) [n]u8 { var result: [n]u8 = undefined; @memset(&result, char); return result;}
pub fn main() void { var width: usize = 10; width += 2; _ = filled(width, '-');}main.zig:10:16: error: unable to resolve comptime value _ = filled(width, '-'); ^~~~~main.zig:10:16: note: argument to comptime parameter must be comptime-knownmain.zig:1:11: note: parameter declared comptime herefn filled(comptime n: usize, char: u8) [n]u8 { ^~~~~~~~If the size really comes from the user, you need memory that’s sized at run time. That’s what allocators are for, in Zig Allocators.
Choosing code at compile time
Section titled “Choosing code at compile time”When an if condition is known at compile time, Zig only compiles the branch that’s taken. The other branch isn’t even checked. A common use is behaving differently per build mode:
const std = @import("std");const builtin = @import("builtin");
pub fn main() void { if (builtin.optimize == .debug) { std.debug.print("debug build: extra checks are on\n", .{}); } else { std.debug.print("optimized build\n", .{}); } std.debug.print("mode: {t}\n", .{builtin.optimize});}Output:
debug build: extra checks are onmode: debug@import("builtin") gives you facts about the current build, like the mode and the target. zig run builds in debug mode by default. Build with zig run -O fast main.zig instead and the program prints:
optimized buildmode: fastIn the fast build, the debug message isn’t hidden or skipped: it’s simply not in the program. This is Zig’s version of C’s #ifdef DEBUG, written with a normal if. The same works with switch on a compile-time value.
comptime var and inline loops
Section titled “comptime var and inline loops”A comptime var is a variable that only lives inside the compiler. Every read and write happens while compiling. You’ll mostly see it as the counter of an inline while, a loop the compiler unrolls into copies of its body:
const std = @import("std");
pub fn main() void { comptime var i = 0; inline while (i < 3) : (i += 1) { std.debug.print("round {d}\n", .{i}); }
comptime var total = 0; inline for (.{ 1, 2, 3, 4 }) |n| { total += n; } std.debug.print("total: {d}\n", .{total});}Output:
round 0round 1round 2total: 10The inline while becomes three print calls with 0, 1 and 2 filled in. The inline for adds up a tuple’s numbers while compiling, so the finished program only contains print with the number 10. You met inline for in Zig Inline Functions; now you know what’s underneath it.
A comptime var can’t hold a run-time value, since it’s gone by the time the program runs:
const std = @import("std");
pub fn main() void { var runtime_n: u32 = 3; _ = &runtime_n; comptime var total: u32 = 0; total += runtime_n; std.debug.print("{d}\n", .{total});}main.zig:7:5: error: cannot store runtime value in compile time variable total += runtime_n; ^~~~~Your own compile errors with @compileError
Section titled “Your own compile errors with @compileError”@compileError("message") stops the build with your message, if the compiler reaches it. Put it in a compile-time if, and you can check your own rules before the program ever runs. A top-level comptime { ... } block is a good place for checks like this:
const std = @import("std");
const max_players = 0;
comptime { if (max_players == 0) @compileError("max_players must be at least 1");}
pub fn main() void { std.debug.print("up to {d} players\n", .{max_players});}main.zig:6:27: error: max_players must be at least 1 if (max_players == 0) @compileError("max_players must be at least 1"); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Change max_players to 4 and the program builds and prints up to 4 players. A settings mistake now fails right away, on your machine, instead of when a user hits it. You’ll use @compileError a lot in generic code, in Zig Generic Functions, to tell callers they passed the wrong type.
Peeking inside the compiler with @compileLog
Section titled “Peeking inside the compiler with @compileLog”std.debug.print runs when your program runs. To see a value while compiling, use @compileLog. It prints what you give it, and it also fails the build on purpose, so you can’t forget it in your code:
const std = @import("std");
pub fn main() void { const x = 5; const y = x * 3; comptime { @compileLog("y is", y); } std.debug.print("{d}\n", .{y});}main.zig:7:9: error: found compile log statement @compileLog("y is", y); ^~~~~~~~~~~~~~~~~~~~~~
Compile Log Output:@as(*const [4:0]u8, "y is"), @as(comptime_int, 15)Each value is shown with its type: the string is a *const [4:0]u8 (a pointer to 4 bytes plus a zero at the end, see Zig Sentinels), and y is a comptime_int with the value 15. Delete the @compileLog line once you’ve seen what you needed. Think of it as print debugging for the compiler.
The branch quota
Section titled “The branch quota”The compiler won’t loop forever on your behalf. Compile-time code gets a budget of 1000 backwards branches (roughly: loop rounds and function calls). Our fibonacci makes a lot of calls, so comptime fibonacci(12) fits, but 25 doesn’t:
const std = @import("std");
fn fibonacci(n: u32) u32 { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2);}
pub fn main() void { const answer = comptime fibonacci(25); std.debug.print("{d}\n", .{answer});}main.zig:5:21: error: evaluation exceeded 1000 backwards branches return fibonacci(n - 1) + fibonacci(n - 2); ~~~~~~~~~^~~~~~~main.zig:5:21: note: use @setEvalBranchQuota() to raise the branch limit from 1000The note tells you the fix. Call @setEvalBranchQuota at the start of the compile-time code to give it a bigger budget:
const std = @import("std");
fn fibonacci(n: u32) u32 { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2);}
pub fn main() void { const answer = comptime blk: { @setEvalBranchQuota(1_000_000); break :blk fibonacci(25); }; std.debug.print("{d}\n", .{answer});}Output:
75025The limit is there to protect you. A bug like a missing base case would otherwise hang your build instead of failing. Raise it when you know the work is big but finite.
What comptime can’t do
Section titled “What comptime can’t do”Compile-time code runs inside the compiler, not on a real computer with a terminal and files. So it can’t:
- print with
std.debug.print, read files, open sockets or do anything else that needs the operating system, - get memory from a heap allocator (though arrays and
vars are fine, as you saw), - use any value that’s only known at run time.
The error for the first one isn’t very friendly. Try comptime { std.debug.print("hi\n", .{}); } and you’ll see something like:
.../lib/std/Io/Threaded.zig:2445:35: error: unable to resolve comptime value const thread = Thread.current orelse return .unblocked; ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~...main.zig:5:24: note: called at comptime from here std.debug.print("hi\n", .{}); ~~~~~~~~~~~~~~~^~~~~~~~~~~~~The error points deep inside the standard library. Read the notes at the bottom: the last called at comptime from here line is your own code. To read a file at compile time there’s a special builtin, @embedFile, which you’ll meet in Zig Builtin Functions.
Be a bit careful with heavy compile-time work. It runs every time the code is compiled, and it’s much slower than the same code at run time. Tables of a few hundred or thousand entries are fine. For really big generated data, a build step (see Zig Build System) is often the better tool. The language reference on comptime has more examples, including how the compiler handles errors in compile-time code.
Practice
Section titled “Practice”1. Powers of two
Section titled “1. Powers of two”Make a top-level constant powers that holds the first 10 powers of two (1, 2, 4, ... 512) as a [10]u64, worked out at compile time. Print the whole table and powers[9].
Hint: use a labeled block with a var table: [10]u64 = undefined; and a running value you double each round.
Show solution
const std = @import("std");
const powers = blk: { var table: [10]u64 = undefined; var value: u64 = 1; for (&table) |*slot| { slot.* = value; value *= 2; } break :blk table;};
pub fn main() void { std.debug.print("{any}\n", .{powers}); std.debug.print("2^9 = {d}\n", .{powers[9]});}Output:
{ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }2^9 = 512for (&table) |*slot| loops over pointers to each slot, so you can write into it with slot.* = value. Because powers is at the top level, the whole block runs while compiling.
2. A sum that’s too big for the budget
Section titled “2. A sum that’s too big for the budget”This program adds up 1 to 5000 at compile time, but it fails with “evaluation exceeded 1000 backwards branches”. Fix it without moving the work to run time.
const std = @import("std");
const total = blk: { var sum: u64 = 0; var i: u64 = 1; while (i <= 5000) : (i += 1) sum += i; break :blk sum;};
pub fn main() void { std.debug.print("{d}\n", .{total});}Hint: each round of the while is one backwards branch, so 5000 rounds need a bigger quota. Set it at the start of the block.
Show solution
const std = @import("std");
const total = blk: { @setEvalBranchQuota(10_000); var sum: u64 = 0; var i: u64 = 1; while (i <= 5000) : (i += 1) sum += i; break :blk sum;};
pub fn main() void { std.debug.print("{d}\n", .{total});}Output:
12502500@setEvalBranchQuota(10_000) gives the block room for 5000 rounds with plenty to spare. The program itself just contains the number 12502500.
3. Check your settings
Section titled “3. Check your settings”Write a program with const tab_width = 0; and a top-level comptime block that stops the build with the message tab_width must be between 1 and 16 when the value is out of range. Then set it to 4 and print tab width: 4.
Hint: if (tab_width < 1 or tab_width > 16) @compileError("...");
Show solution
const std = @import("std");
const tab_width = 4;
comptime { if (tab_width < 1 or tab_width > 16) @compileError("tab_width must be between 1 and 16");}
pub fn main() void { std.debug.print("tab width: {d}\n", .{tab_width});}Output:
tab width: 4With tab_width = 0 (or 20), the build stops with your message and the line it’s on. With 4, the check passes and leaves nothing behind in the program.
- Values are known either at compile time (literals, consts made from them) or at run time (
vars, input, files). comptime exprforces an expression to run while compiling. Code at the top level of a file always does.- A
comptimeparameter must get a compile-time value, so you can use it for array lengths and types. Zig makes one copy of the function per value. - An
iforswitchon a compile-time value only compiles the branch taken, like#ifdefin C. @compileErrorstops the build with your own message;@compileLogprints values while compiling (and fails the build on purpose).- Compile-time code has a budget of 1000 backwards branches; raise it with
@setEvalBranchQuota. - Comptime code can’t do I/O or use heap allocators.
Next up: Zig Generic Functions, where comptime T: type lets one function work for i32, f64 and more.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: comptime: the official section, with compile-time parameters, variables and expressions.
- Zig language reference: @setEvalBranchQuota: how the branch budget works.
- Zig language reference: @compileError and @compileLog: the two compile-time debugging tools.
- Zig in-depth overview: the “Compile-time reflection and compile-time code execution” part shows why Zig has no macros or preprocessor.