#Comptime initialize array with non-contiguous values

1 messages · Page 1 of 1 (latest)

brave storm
#

Hi! Is there an equivalent in Zig of the following C idiom? Or how could I accomplish something like this?

gdt_entry gdt[32] = {
    [0] = (gdt_entry) {
        .limit_0_15 = 0x00,
        .limit_16_19 = 0x00,
    },
    [15] = (gdt_entry) {
      .limit_0_15 = 0xF400,
      .limit_16_19 = 0x1,
    },
};

So basically declaring a constant array with certain but not contiguous values initialized.
I could not find anything in the docs about this.

robust kindle
#

there isn't syntax that looks like this, but you can create the same result with comptime? like ```
const gdt: [32]GdtEntry = gdt: {
var gdt: [32]GdtEntry = undefined;
@memset(gdt, <some default value>);
gdt[15] = <whatever>;

break :gdt gdt;

};

#

depending on your use case an EnumArray might also work

brave storm
#

Ah great that seems to work! I wasn't familiar with that syntax, thanks.

twilit hearth
#

Or since it's comptime, use comptime operators:

const gdt = (.{default_value} ** 16) ++ .{whatever} ++ (.{default_value} ** 15);

Someone check if it works correctly (as long as default_value and whatever don't need to coerce), I can't rn.