Do comptime variables have "static" lifetime?

I’m working on a problem and the easiest way to solve it is to return a slice from a comptime variable locally. In C++, this can be achieved by having something declared as static as that designates the variable to have extended lifetime (and thus is safe to return pointers to those variables). Is this the same for Zig? I checked the documentation but didn’t find anything that immediately seemed obvious.

As far as I undestand, static variables are basically global variables that have the advantage of not polluting the global namespace because they are defined inside a function’s lexical scope.

The closest thing you can do in Zig is this:

fn foo() *bool {
   const MyStruct = struct {
      var my_static_variable: bool = false;

   return &MyStruct.my_static_variable;

More in general though, I think that static variables are not all that useful if you have namespaces, so I would recommend just moving the full definition of MyStruct outside of the function and using it as a normal namespaced global.

1 Like

Interesting! Thanks for the quick reply. I found a different way around my problem, but I’m very interested in this issue in general. Originally, I had returned a slice from a comptime var and in my limited testing, I was able to see that the stack memory had not been corrupted (which lead me to believe that at least in the test I did, they had static-like lifetime). To be very clear though, the values were used immediately after the function call so this could have just been a little “fortunate” slice of undefined behaviour.