assert

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Sep 11 06:07:26 UTC 2024


On Tuesday, September 10, 2024 10:01:53 PM MDT f via Digitalmars-d-learn 
wrote:
> i mean , is this a bug?

No, it's not a bug. Assertions with an expression that is known to be false
at compile time are treated as special. They are always left in the
generated code so that they will kill your program if you ever hit that line
of code.

So, assertions which actually need to be validated at runtime will be
compiled out with -release, but assert(false) is always there, and with
-release, instead of throwing an AssertError, it immediately terminates the
program.

One common use case for this would be something like

auto foo(int i) nothrow
{
    try
    {
        ...
    }
    catch(Exception)
    {
        assert(false, "It should be impossible for this code to throw.");
    }
}

where you have code that you know will never throw given the input that
you're giving it, but it's not nothrow, because it could throw under other
circumstances. And so in order to call that code within a nothrow function,
you wrap it in a try-catch block, and then just in case you screwed up, and
it does somehow throw, the assertion is triggered even with -release, and
your program is terminated instead of continuing in an invalid state.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list