Confusion over enforce and assert - both are compiled out in release mode

Andrew Chapman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 27 03:46:53 PDT 2017


On Sunday, 27 August 2017 at 10:37:50 UTC, Moritz Maxeiner wrote:
> On Sunday, 27 August 2017 at 10:17:47 UTC, Andrew Chapman wrote:
>> On Sunday, 27 August 2017 at 10:08:15 UTC, ag0aep6g wrote:
>>> [...]
>>
>> Thanks, that explains it.  I think it's a bit of a shame that 
>> the "in" blocks can't be used in release mode as the clarity 
>> they provide for precondition logic is wonderful.
>
> If you need that, you could compile using ldc in release mode 
> (which you probably want to do anyway):
>
> --- test.d ---
> import std.exception;
> import std.stdio;
>
> void foo(int x) in { enforce(x > 0); } body
> {
>
> }
>
> void bar(int x) in { assert(x > 0); } body
> {
>
> }
>
> void baz(int x) in { if (!(x > 0)) assert(0); } body
> {
>
> }
>
> void main()
> {
>     (-1).foo.assertThrown;
>     (-1).bar;
>     (-1).baz;
> }
> --------------
>
> $ ldc2 test.d
> -> failed assert in bar's in contract terminates the program
>
> $ ldc2 -release test.d
> -> failed assertThrown in main terminates the program
>
> $ ldc2 -release -enable-contracts test.d
> -> failed assert in baz's in contract terminates the program
>
> $ ldc2 -release -enable-contracts -enable-asserts test.d
> -> failed assert in bar's in contract terminates the program

Oh interesting.  Does DUB support passing through the 
--enable-contracts flag to ldc?  Also, if this is an ldc specific 
thing it's probably not a good idea i'd imagine, since in the 
future one may want to use a GDC, or DMD?


More information about the Digitalmars-d-learn mailing list