assert(false)

monarch_dodra monarchdodra at gmail.com
Thu Jun 20 13:37:11 PDT 2013


On Thursday, 20 June 2013 at 19:57:16 UTC, H. S. Teoh wrote:
> On Thu, Jun 20, 2013 at 08:48:38PM +0100, 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?
>
> I consider that good practice, so that when an unexpected code 
> path was
> followed, the program terminates instead of proceeding to 
> potentially do
> dangerous things.
>
>
> T

I'd say yes.

It is usually "bad practice" to keep an assert in release 
("assert(false)"), because the code should already have been 
checked, and you shouldn't pay for the check in release.

BUT: Since the code is theoretically unreachable, there is no 
real world penalty to the check anyway, so you might put it in 
anyways, on the off chance it saves your but (IMO).

Another interesting thing is that assert(0) can be used to tell 
the compiler "I don't need to declare a return, because I don't 
ever plan for the *runtime* to reach this spot, even if you can't 
statically see that". Instead of doing an assert(0), followed by 
a dummy return, you may omit the return statement entirelly. EG:

int find10(R a)
{
     foreach(i, e; a)
         if (e == 10)
             return i;

     assert(0);
     //no need for a return here.
}

This is particularly relevant when "sometimes" the compiler 
statically sees you can't reach the end of the code (-O -inline 
release), yet doesn't see it in a debug release.

In that case, you'd either be doomed to put a return, and get a 
"statement not reachable" error, or leave it blank, and get a "no 
return statement" error.

assert(0) solves this problem.


More information about the Digitalmars-d-learn mailing list