No bounds checking for dynamic arrays at compile time?

Walter Bright newshound2 at digitalmars.com
Thu Dec 13 02:53:17 PST 2012


On 12/13/2012 2:40 AM, bearophile wrote:
> Walter Bright:
>
>>> void main() {
>>>     int[5] x;
>>>     x[$] = 1;
>>>     enum size_t n = 2;
>>>     x[$ + n] = 2;
>>> }
>>
>> The compiler does that already.
>
> I am compiling that little program with
>
> dmd -w test.d
>
> And I see no compilation errors.

Well, it should for those cases.


> See also here, it gives a run-time error:
> http://dpaste.dzfl.pl/a62a10aa
>
>
>>> void main() {
>>>     int[] x = new int[5];
>>>     x[$] = 1; // easy
>>>     x[x.length] = 1; // idem
>>>     enum size_t n = 2;
>>>     x[$ + n] = 2; // not too much hard if n is unsigned
>>>     x[x.length + n] = 2; // idem
>>> }
>>
>> I just don't see the point in adding flow analysis for that,
>
> I think that doesn't require flow analysis.

Yeah, it does, unless you care to put in the compiler a long list of special 
cases. For example, what about $+$, n+$, $+$-$+1, $<<n, etc.? These sort of turn 
into whack-a-mole games.



>> and it'll ding you at runtime anyway.
>
> This thread is about spotting mistakes at compile-time, that is one of the main
> advantages of having a static typing in the first place.

Since the bug is caught anyway, such is an extremely low priority because it's 
got such a low payoff.



More information about the Digitalmars-d mailing list