#When is it useful to take the address of a parameter in Zig?

1 messages · Page 1 of 1 (latest)

sullen mantle
#

While helping a new user on Ziggit I encountered the following: every time that you take the address of a function parameter in Zig, a new local stack copy of the parameter is created. I may very well be missing something, but it proved true in the situations and optimization modes that I tried.

While this does make some sense with how arguments are passed in most calling conventions, I now wonder: what is a situation where it is useful to take a pointer to a function parameter without explicitly making a local copy?

dim swallow
#

the copy could probably be elided with Parameter Reference Optimization (converting f(x: X) into f(x: *const X) when X is "big"). Apart from that, taking the address alone shouldn't be enough to have it be a local: escaping or observing the address should Id think. If you just use the address normally, optimizer could see it no different than a constant. But if the address escapes, it has to live somewhere valid, and a value semantically doesn't have a address, so it must store it to a local.

sullen mantle
#

I figured that the big struct case might be where this could avoid a copy, but as far as I can tell that is not what happens currently.

#

Also, since each parameter arg is immutable and thus taking &arg results in a *const, I assume that new copies being created each time a reference is observed is probably unintended? The behavior that triggered the investigation was:

pub fn printRef(v: u64) void {
    std.debug.print("{}\n", .{&v});
    std.debug.print("{}\n", .{&v});
    std.debug.print("{}\n", .{&v});
}

producing three different addresses on all optimization modes.

dim swallow
#

that might be a bug