assert(false)

Jonathan M Davis jmdavisProg at gmx.com
Thu Jun 20 14:15:31 PDT 2013


On Thursday, June 20, 2013 21:47:55 Joseph Rushton Wakeling wrote:
> On 06/20/2013 09:28 PM, Ali Çehreli wrote:
> > On 06/20/2013 12:48 PM, Joseph Rushton Wakeling wrote:
> >> Is it considered good/recommended practice to insert an assert(false)
> >> statement in parts of the code that should be unreachable? Or simply an
> >> optional choice that may be useful for debugging?
> > 
> > And a reminder that assert(false) (and assert(0)) is never removed from
> > code (even when other asserts are). So, they are always there to prevent
> > the program from producing unexpected results.
> 
> OK. I noticed them present in some code in Phobos, and there's a place in
> RandomSample where one could reasonably expect to see one but there isn't
> right now. I was considering whether to include it in some patches I'm
> preparing.

I definitely use assert(false) for what is supposed to be unreachable code. The 
two prime places that I can think of off the top of my head are

1. In a catch block when it's supposed to be impossible for the try block to 
throw (e.g. when calling format in a nothrow function, and you know that 
format won't throw with the arguments that you're passing it).

2. In the default case of a switch statement when the default case should be 
unreachable.

If those ever _are_ reached, then your code has serious problems, and killing 
the program is almost certainly a good thing.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list