rust

Are there any performance advantages in using `unreachable!` vs `panic!`?


Is the existence of unreachable! macro purely for the sake of clarity when reading code, or does it provide any functional advantages?


Solution

  • Yes, the unreachable! macro (and unimplemented! too) are purely for clarity. They are implemented to directly forward to panic!.

    #[macro_export]
    #[stable(feature = "rust1", since = "1.0.0")]
    macro_rules! unreachable {
        () => ({
            panic!("internal error: entered unreachable code")
        });
        ($msg:expr) => ({
            unreachable!("{}", $msg)
        });
        ($fmt:expr, $($arg:tt)*) => ({
            panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
        });
    }
    
    #[macro_export]
    #[stable(feature = "rust1", since = "1.0.0")]
    macro_rules! unimplemented {
        () => (panic!("not yet implemented"))
    }
    

    Not to be confused with the unreachable intrinsic (accessible in stable Rust via the unreachable or debug_unreachable crates), which unsafely asserts a branch is totally unreachable. This allows the branch to be completely removed when optimizing. It could lead to undefined behavior if the assertion turns out to be wrong, compared with unreachable!() which only panics.