automatic int to short conversion - the HELL?

Jarrett Billingsley jarrett.billingsley at gmail.com
Fri Sep 19 07:21:12 PDT 2008


On Fri, Sep 19, 2008 at 9:45 AM, Ary Borenszweig <ary at esperanto.org.ar> wrote:
> Jarrett Billingsley wrote:
>>
>> On Fri, Sep 19, 2008 at 9:29 AM, Ary Borenszweig <ary at esperanto.org.ar>
>> wrote:
>>>
>>> bearophile wrote:
>>>>
>>>> Ary Borenszweig:
>>>>>
>>>>> No, no. In Java it's an error, an explicit cast is required.
>>>>> http://www.programmersheaven.com/2/FAQ-JAVA-Type-Conversion-Casting
>>>>> Which is perfect. It expresses the intents of the programmer:
>>>>
>>>> About such matters I suggest you all to also take a look at how Ada
>>>> works.
>>>> Ada was designed first of all to create reliable software, so avoiding
>>>> casting-derived bugs too is essential.
>>>> D tries to avoid some of the pitfalls of C, to be a language less
>>>> bug-prone: casts is where D has to improve still in such regards. Time
>>>> ago
>>>> (when I was more a D newbie) I have already had a bug in my code because
>>>> of
>>>> a casting bug:
>>>>
>>>> import std.stdio;
>>>> void main() {
>>>>   int n = -5;
>>>>   int[] a = [1, 2, 3];
>>>>   writefln(a.length > n); // prints false
>>>> }
>>>>
>>>> A well designed language, even a system language like Ada or D, must
>>>> avoid
>>>> such kinds of bugs, regardless the amount of ignorance of the
>>>> programmer.
>>>
>>> Wow. At first, I thought that was already fixed. Now I've written that
>>> code,
>>> compiled it and run it and saw it gives false. Ok, I know a.length is an
>>> uint because logically it cannot be negative. But... shouldn't it be an
>>> int
>>> to avoid this kind of bugs?? You loose nothing doing this. You are never
>>> going to need an array of 2147483647 positions, much less a bigger array.
>>>
>>> I've checked C#, which has uint as a type. The length of an array is an
>>> int,
>>> not an unit. A much better choice.
>>
>> signed-unsigned comparison is, I think, a slightly larger problem than
>> the type of array.length ;)
>
> But if the length of an array is an uint, if you compare it to an int then
> what bearophile has just shown might happen.
>
> Now, if the length of an array is an int, but which is guaranteed to be
> always positive or zero, then if you compare it to an int or an unit, you
> always get the desired result.
>
> Conclusion: you avoid a bug to happen at zero cost.
>
> So... why not?
>

The point is that signed-unsigned comparison _in general_ is a bad
thing, and array.length-int is just one manifestation of it.  If
signed-unsigned comparison were made illegal, this would be an error.


More information about the Digitalmars-d-learn mailing list