What should happen when the assert message expression throws?

Quirin Schroll qs.il.paperinik at gmail.com
Mon Jan 9 09:39:32 UTC 2023


On Friday, 25 November 2022 at 15:33:07 UTC, kdevel wrote:
> On Friday, 25 November 2022 at 14:38:57 UTC, Ali Çehreli wrote:
>> On 11/25/22 05:32, kdevel wrote:
>
>> If that assertion fails, the program is in an invalid state.
>
> [reordering ...]
>
>> > int main ()
>> > {
>> >     int a = 1;
>> >     try
>> >        assert (a == 0);
>> >     catch (Throwable t)
>> >        {}
>> >     return 0;
>> > }
>> >
>> > Which line makes the program enter the "invalid state"?
>
> Is it in the "invalid state" right after the condition has been 
> evaluated or not before the AssertError has been thrown? What 
> if the program is compiled with -release? Is it still in 
> "invalid state"?

I don’t know for D because the spec is not that precise. In C++, 
which is comparable in this regard, the invalid state (aka. 
undefined behavior, UB) is entered when executing a code that is 
UB is inevitable. An optimizer may reason:
* Throwable is caught; if it happens to be an Error, that is UB.
* The only statement in the try block succeeds or throws an 
Error. (It may thus remove the assert and the try-catch entirely.)
* Variable a is never re-assigned, it is effectively const.
* Therefore, the assert always fails. (It must not be treated 
like assert(false), tho.)
* Therefore, any execution will throw and catch an Error. The 
program may be replaced by virtually anything, including doing 
nothing at all.

No clue if D allows or forbids UB back-propagation. Note that in 
C++, a lot more simple things are UB which means a lot more 
things risk UB. Signed arithmetic in C++ would not qualify for 
D’s @safe because signed overflow is UB in C++ (not unsigned, 
tho); signed overflow it is defined as being modulo 2ⁿ in D.


More information about the Digitalmars-d mailing list