The unreachable statement – asserting the impossible
Have you ever been absolutely certain that a piece of code should never be executed? In Zig, you can assert this certainty using the unreachable statement. It's like telling the compiler, "If we ever get here, something has gone horribly wrong."
In Debug and ReleaseSafe modes, reaching an unreachable statement will cause the program to panic with the message "reached unreachable code." In ReleaseFast and ReleaseSmall modes, the compiler assumes that unreachable code paths are impossible and may optimize accordingly.
Here's a basic example:
pub fn main() void {
const x = 1;
const y = 2;
if (x + y != 3) {
unreachable; // We assert that this code should never be reached
}
// Continue with the rest of the program
}
In this code, we check if x + y does not equal 3. Since 1 + 2 is always 3, the condition is false, and unreachable is never...