Where does a temporary variable live in a statement

Let’s say I have the following struct

const Temp = struct {
  buf: [4]u8,
  fn init() Temp {
    return .{.buf = @splat(0)};
  }
  fn slice(self: *const Temp) []const u8 {
    return &self.buf;
  }
};

pub fn main() !void {
  const slice = Temp.init().slice();
  _ = slice;
}

does slice point to valid memory for the entirety of main? if so, does Temp.init() implicitly create an anonymous variable?

1 Like

This might work with the current implementation of the compiler, however as far as I know the language only guarantees that the temporary value lives as long as the expression its used in (unless it’s a comptime-known value, so if you do comptime Temp.init().slice() then it should work).

Also I’d suggest to show the full code example where you want to have this, so we can give you suggestions on what alternatives to use.

1 Like

I don’t have an actual problem to solve. This came up from another discussion and I want to check my understanding about how Zig handles temporaries.

So Zig still does not have a defined semantic for how it handles temporaries, is that correct?

No, in general defining clear language specs is still an open TODO
For now though, the existence of x86_64 backend fails to reuse temporary stack values resulting in greater stack usage and potential overflow · Issue #24183 · ziglang/zig · GitHub seems to suggest that they do want to reuse stack space from temporary values.

3 Likes