Inserting sentinel values in arrays

The compiler currently doesn’t mind if I insert a sentinel value anywhere in a sentinel-terminated array:

    var nums = [_:0]u32{1, 2, 3, 4, 5, 6};
    nums[2] = 0; // Insert the sentinel value at the third position
    for (nums) |n| @import("std").debug.print("{} ", .{n});

(Prints 1 2 0 4 5 6.)

This wasn’t shocking to me, but it did make me wonder if there has been any discussion about this and whether I can reasonably expect to always be allowed to insert sentinel values wherever I like in the future.

I also thought it was interesting that I was able to print a [n:0]u8 string that contained the 0 sentinel “Null Character” in the middle. The entire string printed and the Null Character was simply ignored.

Am I correct in thinking that using sentinel-terminated types is generally for C interop (or wizardry) and that the Zig compiler will likely only be concerned with enforcing the sentinel value at the end of a sequence (as in issue 3962) now and in the future?

2 Likes

Update: I posted a link to this question on the Zig Discord server and so far the discussion hasn’t changed my impression that:

  1. This is the expected behavior
  2. Zig is only concerned with enforcing the sentinel in the terminal spot
  3. Sentinel termination is probably not something you’re going to use a lot in pure Zig code, but can be important when working with external libraries, etc.
2 Likes