4 ms·
Sometimes you do it because the compiler insists a case (that really can never happen) needs to be handled. It happens a lot to me in Rust and Go.
by someguy1234 11y ago
Sometimes you do it because the compiler insists a case (that really can never happen) needs to be handled.
It happens a lot to me in Rust and Go.
- masklinn 11y agoRust has support for "this can not happen" in core: http://doc.rust-lang.org/core/macro.unreachable!.html http://doc.rust-lang.org/core/macro.unreachable!.html GCC also has an extension for that: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005funreachable-4214 https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index... which Clang supports: http://clang.llvm.org/docs/LanguageExtensions.html#builtin-unreachable http://clang.llvm.org/docs/LanguageExtensions.html#builtin-u...
- cpeterso 11y agoNote that gcc and clang's __builtin_unreachable() are optimization pragmas, not assertions. If control actually reaches a __builtin_unreachable(), your program doesn't necessarily abort. Terrible things can happen such as switch statements jumping into random addresses or functions running off the end without returning: https://raw.githubusercontent.com/bjacob/builtin-unreachable-study/master/notes https://raw.githubusercontent.com/bjacob/builtin-unreachable...
- nightpool 11y agoSure, these aren't for defensive programming—they're for places where you know a location is unreachable, but your compiler can't prove it for you. The example given in the rust docs, for example, is a match clause with complete guard arms (i.e. if n < 0 and if n >= 0).