Hacker News new | ask | show | jobs
by someguy1234 3729 days 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.

1 comments

Note 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...

Sure, 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).