What are sentinals?

In C programming language, it is common to terminate arrays of integers or characters with 0, and arrays of pointers with null.
C strings are pointers to characters, that cannot contain 0, and there is a 0 marking the end of the string (0 terminated strings).

Sentinels are not useful in zig. It is a feature that makes sense only for C interfacing.

Zig string constants are actually zero terminated arrays and the only reason for that is C API usability.
For example:

const c = @cImport(@cInclude("stdio.h"));

pub fn main() void {
    const s: [:0]const u8 = "Hello World\n";
    _ = c.puts(s.ptr);
}

Run the example using: zig run example.zig -lc
C library puts function, prints a zero terminated string.
This works because "Hello World\n" is a zero terminated array.
s is a zero terminated slice (pointer and size) and s.ptr is the pointer to the zero terminated string.

See also: Conversions between slices and pointers with and without sentinel

2 Likes