Confused about null terminated array

Why test1 fail but test2 success?
zig version 0.8.1

test "test1" {
    var array : [16:0]u8 = undefined;
    try testing.expect(array[16] == 0);

test "test2" {
    const array : [16:0]u8 = undefined;
    try testing.expect(array[16] == 0);
1 Like

this fails in this way because the second one uses const and thus the data cannot change and becomes comptime known. through this it is able to infer that [16] is going to be the sentinel and thus be 0.

for test1, the data is forced to be runtime data through the use of var and all the bytes are set to be 0xaaaa... which does not equal 0.


That was a great explanation. Thanks.

I still can not understand.In test1,the 16 bytes data are unknown,but the sentinel isn’t known as 0?

it’s a safety mechanism so that you don’t accidentally operate on undefined memory

imo the second should be a compile error

1 Like