#Is this code guaranteed to behave as expected?

1 messages · Page 1 of 1 (latest)

autumn grove
#
const std = @import("std");
fn foo(newval: ?u32) u32 {
    const static = struct {
        var foo: u32 = 1337;
    };
    if(newval) |v| static.foo = v;
    return static.foo;
}

test {
    try std.testing.expectEqual(@as(u32, 1337), foo(null));
    try std.testing.expectEqual(@as(u32, 69), foo(69));
    try std.testing.expectEqual(@as(u32, 69), foo(null));
}
lunar warren
#

sure, so long as you're always single threaded

coral galleon
#

yes, it is exactly the same as

var foo_val: u32 = 1337;
fn foo(newval: ?u32) u32 {
    if(newval) |v| foo_val = v;
    return foo_val;
}
autumn grove
#

oh no I mean in this specific case

lunar warren
#

yeah

autumn grove
#

good

lunar warren
#

foo is just a normal global variable

autumn grove
#

I was worried that the semantics of initializing a global in a function weren't defined

lunar warren
#

nah, they is

autumn grove
#

good ^_^

lunar warren
#

all declarations are first analysed, and they're initialised to a comptime-known value, in this case, it's initialised to 1337

#

since all that happens before compilation, there aren't really any runtime global init semantics

#

it just "is" 1337 as soon as it exists