liveBook · Manning

Lazy evaluation

As explained in Systems Programming with Zig

Lazy evaluation is an evaluation strategy that delays computing an expression until its value is needed.

Lazy evaluation delays computing an expression until its value is needed. In Zig, this means an unused function or constant can be syntactically correct but semantically wrong without the compiler noticing. section 4.1.3

This behavior is useful for cross-platform code. When the target operating system is known at comptime, the compiler ignores branches that will not be evaluated. A Linux build need not include the Windows implementation, or vice versa. section 4.1.3

const builtin = @import("builtin");

fn crossPlatformFunction() void {
    if (builtin.os == .linux) {
        linuxVersion();
    } else if (builtin.os == .windows) {
        windowsVersion();
    }
}

The target operating system selects which implementation is evaluated. section 4.1.3

Checking a comptime wordlist

Reference the parsed words with @compileLog to make the compiler evaluate them and print the result for an eyeball check. Remove the log afterward: code containing @compileLog will not fully compile. section 4.1.3

comptime {
    @compileLog(words);
}

This comptime block references and logs the parsed words. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Defines lazy evaluation and explains its compiler trade-off through target selection and a validation caveat, without detailing compiler internals.
Examples
Uses a parsed wordlist logged at compile time and a Linux-versus-Windows function branch.
What you can do after
Diagnose/debug comptime code with @compileLog to force evaluation and inspect a value.
How it connects
Connects lazy evaluation to compile-time evaluation, cross-platform programming, and semantic correctness.

Also explained in

Compare how 16 books explain lazy evaluation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.