assert vs enforce?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Jan 22 17:02:36 PST 2011


assert also disappears when building in release mode.

On 1/23/11, Robert Clipsham <robert at octarineparrot.com> wrote:
> On 23/01/11 00:33, Sean Eskapp wrote:
>> What's the difference between assert and enforce in D?
>
> Use assert() for something that must almost be true, regardless of user
> input, or anything else.
>
> enforce() on the other hand is for things which may or may not be true.
> The source code should clear things up:
> ----
> T enforce(T)(T value, lazy Throwable ex)
> {
>      if (!value) throw ex();
>      return value;
> }
> ----
> So it's essentially just shorthand for throwing an exception.
>
> Example:
> ----
> void main(string[] args)
> {
>      enforce(args.length > 2, "The user needs to pass the correct
> parameters");
>      assert(1+1==2, "If this isn't true, the application should terminate");
> }
> ----
>
> --
> Robert
> http://octarineparrot.com/
>


More information about the Digitalmars-d-learn mailing list