3 ms·
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 de
by tough 1y 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.