Zig NEWS

Pyrolistical
Pyrolistical

Posted on

Puzzler: Impossible slice?

I loved Java Puzzlers and whenever I encounter some unexpected behaviour, I turn it into a puzzler for others to enjoy.

Here is a "fill in the blank" Zig puzzler:

const std = @import("std");

test {
    // YOUR CODE HERE

    try std.testing.expectEqual(0, slice.len);
    try std.testing.expectEqual(42, slice[0]);
}
Enter fullscreen mode Exit fullscreen mode

All you need to do is make the test pass. But Zig is zero indexed. How can the slice both have zero length AND the first element is 42???

Pause here if you want to take a stab at this puzzler.

Hints will be after the cat picture.

Image description

Hint 1. There is no undefined behaviour memory trickery here. It is plain normal valid Zig.
Hint 2. There is nothing tricky going on with std.
Hint 3. slice is indeed a slice.

The solution will be after the cat picture.

Image description

Solution: The slice is sentinel terminated.

const slice: [:42]const u8 = &[_:42]u8{};
Enter fullscreen mode Exit fullscreen mode

Sentinel terminated slices don't include the sentinel as part of .len. In memory, slice is 1 byte long, with the value 42.

An alternative solution is to use an array.

const slice: [0:42]u8 = undefined;
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
gnarz profile image
gz@tset.de

nice one :)

Collapse
 
guidoschmidt profile image
Guido Schmidt

Love this idea of puzzles for a post 👍🏼 thanks for sharing 🙏🏼