A strange div bug on Linux x86_64, (both dmd & ldc2): long -5000 / size_t 2 = 9223372036854773308

bachmeier no at spam.net
Thu Aug 13 13:33:19 UTC 2020


On Thursday, 13 August 2020 at 11:40:59 UTC, jmh530 wrote:
> On Thursday, 13 August 2020 at 10:40:33 UTC, bachmeier wrote:
>> 
>> [snip]
>>
>> Imagine a new user to the language wanting to compute the mean 
>> of an array of numbers:
>>
>> import std;
>> void main()
>> {
>>     long sum = 0;
>>     long[] vec = [-112, 2, 23, -4];
>>     foreach(val; vec) {
>>         sum += val;
>>     }
>>     writeln(sum/vec.length);
>> }
>>
>> This is inexcusable.
>
> It's certainly annoying, but if there were an equivalent length 
> function in C, then it would have the same behavior. 
> Unfortunately, this is one of those things that were carried 
> over from C.

The source of wrong behavior is vec.length having type ulong. It 
would be very unusual for someone to even think about that.

> Also, note that the true mean of vec above is -22.75, which 
> wouldn't even be the result of your function if length returned 
> a signed variable, because you would be doing integer division. 
> A person who comes to D without ever having programmed before 
> would get tripped up by that too.

That's why that behavior needs to be changed as well. It's 
horrible to implicitly cast from int to double when doing so 
results in obviously wrong behavior. Hopefully there won't be any 
more talk about safe by default as long as the language has 
features like this that are obviously broken and trivially fixed.


More information about the Digitalmars-d mailing list