enforce (i > 0) for i = int.min does not throw

Steven Schveighoffer schveiguy at yahoo.com
Thu Feb 1 01:23:33 UTC 2018


On 1/31/18 6:19 PM, Azi Hassan wrote:
> On Saturday, 27 January 2018 at 14:13:49 UTC, kdevel wrote:
>> I would expect this code
>>
>> enforce3.d
>> ---
>> import std.exception;
>>
>> void main ()
>> {
>>    int i = int.min;
>>    enforce (i > 0);
>> }
>> ---
>>
>> to throw an "Enforcement failed" exception, but it doesn't:
>>
>> $ dmd enforce3.d
>> $ ./enforce3
>> [nothing]
> 
> I wonder if it's caused by a comparison between signed and unsigned 
> integers.

No, the answer is, there's a shortcut optimization used by the compiler. 
See the discussion elsewhere in this thread.

> 
> import std.stdio;
> 
> void main ()
> {
>      int zero = 0;
>      writeln(int.min > 0u);
>      writeln(int.min > zero);
> }

Note that comparing the literal int.min will get folded into a constant, 
and do the right thing. You have to assign it a variable to see the 
incorrect behavior:

int i = int.min;
writeln(i > 0);

-Steve


More information about the Digitalmars-d-learn mailing list