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

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 27 03:37:50 PDT 2017


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:
>> On 08/27/2017 12:02 PM, Andrew Chapman wrote:
>>> However, I am finding that BOTH enforce and assert are 
>>> compiled out by dmd and ldc in release mode.  Is there a 
>>> standard way of doing what enforce does inside an "in" 
>>> contract block that will work in release mode?
>>> 
>>> I'm guessing I should write my own function for now.
>> The whole `in` block is ignored in release mode. Doesn't 
>> matter what you put in there. Nothing of it will be compiled.
>
> 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


More information about the Digitalmars-d-learn mailing list