Const variables and copying on assignment

From experience I know that assigning a const to a const doesn’t create a copy. i.e. the following test works.

test "constness" {
    const B = struct {
        a: i128 = 1,
    };

    const a: B = .{};
    const b = a;
    try std.testing.expectEqual(&a, &b);
}

But I’ve not found anywhere in the language documentation that states this is the behaviour. Does zig guarantee no copy here or is it only elided if the optimizer can prove that no copy is needed?

Are there other situations where assigning a const to a const might create a copy?

In other words, outside of using some extra stack memory to store the pointer in the second snippet, is there any practical difference between using const b = a and const b = &a assuming a is also const.

Cheers.

1 Like

Two compile time known constants that are equal to each other can just be the same constant. It doesn’t affect anything if they are the same or different locations, it just uses less space.

They are also not necessarily on the stack, since they are comptime known. They are probably in static read only memory/part of the executable.

This isn’t a zig thing, I’d expect any competent compiler to do this.

yes, before b was equal to a so were the same thing. Now b is the address of a, which is a different, but also statically known thing. I would expect this b wouldn’t even be in static RO memory, but inlined into the instructions as the address of a is compile time known

2 Likes

The reason for asking is that I’m often doing const shortname = field.within.a.nested.structand then work with shortname in the remainder of the function. I’m wanting to make sure that is always safe to do (assuming it is all const), or whether it is safer to just use a pointer.

It sounds like the answer is it is fine to use because in simple cases like this, the compiler will see that neither have changed during the scope of my function and determine no copy is required?

Yes, if it is ever not safe it would be a major bug, for your simple case anyway.
It ofc depends on the value you give to the constant, but if you’re not doing any weird things, you can assume it is safe.

Zig tries to make unsafe things more annoying and visibly distinct, without stopping you entirely, cause unsafe things are useful.

1 Like