top | item 44845375

(no title)

spiffyk | 6 months ago

This post shows how versatile Zig's comptime is not only in terms of expressing what to pre-compute before the program ever runs, but also for doing arbitrary compile time bug-checks like these. At least to me, the former is a really obvious use-case and I have no problem using that to my advantage like that. But I often seem to overlook the latter, even though it could prove really valuable.

discuss

order

dwattttt|6 months ago

I love the idea, but something being "provable" in this way feels like relying on optimisations.

If a dead code elimination pass didn't remove the 'comptime unreachable' statement, you'll now fail to compile (I expect?)

tough|6 months ago

The key insight here is that `comptime unreachable` isn't relying on optimizations at all—it's a fundamental part of Zig's lazy evaluation semantics.

Unlike dead code elimination (which is an optimization pass that removes provably unused code), Zig's compile-time evaluation is deterministic and mandatory. When you use `inline .a, .b`, the compiler must generate separate instantiations for each enum variant. Within each instantiation, `ab` becomes a comptime-known value, making the inner switch deterministic at compile time.

This is similar to how C++ template instantiation works: the compiler doesn't "optimize away" unused template specializations—it simply never instantiates them in the first place. Zig's `comptime unreachable` works the same way: unreachable branches are never even considered for compilation because the control flow is resolved at compile time.

The difference matters because optimization-based approaches can vary between compiler versions or optimization levels, while Zig's semantic guarantees remain consistent. This makes `comptime unreachable` suitable for expressing static invariants that must hold regardless of compilation flags.

teiferer|6 months ago

It's inherently an incomplete heutistic. Cf. the halting problem.

Doesn't mean it's not useful.

anonymoushn|6 months ago

A lot of Zig relies on compilation being lazy in the same sort of way.