Container level variable address at comptime

From the documentation:

Container level variables have static lifetime and are order-independent and lazily analyzed. The initialization value of container level variables is implicitly comptime. If a container level variable is const then its value is comptime-known, otherwise it is runtime-known.

I wonder if I could pass the address of a static variable as a comptime argument to a function. But apparently the compiler is not ok with that.

Does it make sense to say that the value of the variable might not be known, but its address should be?

const std = @import("std");

fn Store(comptime addr: *f32) type {
    return struct {
        const Self = @This();

        addr: *f32 = addr,

        fn write(self: *Self, value: f32) void {
            self.addr.* = value;
        }

        fn read(self: *Self) f32 {
            return self.addr.*;
        }
    };
}

pub fn main() !void {
    var x: f32 = undefined;

    const s = Store(&x){};

    s.write(23);
    std.debug.print("{}\n", .{s.read()});
}

x is not a container level variable in this example. You would have to declare it outside of main for it to be one (or otherwise place it in a struct/union/enum definition).

With a couple other fixes, this works:

const std = @import("std");

fn Store(comptime addr: *f32) type {
    return struct {
        const Self = @This();

        addr: *f32 = addr,

        fn write(self: *const Self, value: f32) void {
            self.addr.* = value;
        }

        fn read(self: *const Self) f32 {
            return self.addr.*;
        }
    };
}

var x: f32 = undefined;
pub fn main() !void {
    const s = Store(&x){};

    s.write(23);
    std.debug.print("{}\n", .{s.read()});
}
4 Likes

damn you are right, silly mistake! thanks for pointing it out!

You may find helpful the first two answers of this thread:

1 Like