Use compile-time code to initialize an array

The code is from the language reference, in Array

// use compile-time code to initialize an array
var fancy_array = init: {
    var initial_value: [10]Point = undefined;
    for (&initial_value, 0..) |*pt, i| {
        pt.* = Point{
            .x = @intCast(i),
            .y = @intCast(i * 2),
        };
    }
    break :init initial_value;
};

The document says use compile-time code, but is this really true?

Thanks.

1 Like

The code in question is in the global scope (outside any functions) and it’s initializing a global variable. Zig doesn’t have C++'s concept of executing runtime code before main() (and thank god for that), so the code will run at comptime, even if not annotated with comptime.

PS: e.g. if you sift through all the noise here: Compiler Explorer, you’ll find the ‘comptime-populated’ array:

example.fancy_array:
        .long   0
        .long   3
        .long   6
        .long   9
        .long   12
        .long   15
        .long   18
        .long   21
        .long   24
        .long   27
8 Likes