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.
dwattttt|6 months ago
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
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
Doesn't mean it's not useful.
anonymoushn|6 months ago