I've been newly exploring D for a very short while now, and, exploring Array functionality, I came upon this funny bit of code off of a badly written tutorial.

import std.stdio;

void main()
{
   int[] intArray;
        
   intArray[0] = 42;
   intArray[1] = 54;
   intArray[2] = 91;

   writefln("The length of intArray is %d.", intArray.length);
}

This compiles, believe it or not, and doesn't throw any errors or warnings whatsoever, but obviously for people who know D, this will throw a core.exception.RangeError: Range violation when run.

Why? Because Dynamic Arrays in D are not dynamic à-la-JavaScript, they can just be resized. The missing line comes directly after the array declaration:

intArray.length = 3;

Now, given that doing int[] myArray initializes a dynamic array with length 0, why is there no bounds checking on this? Why is the compiler not even throwing a warning telling me the dynamic array's length has not been initialized or that I'm trying to access data which is potentially out of bounds?

Static arrays throw out of bounds errors on compilation when there's a mismatch, but why not dynamic arrays?

I thought D was supposed to be a language allowing safer programming than C. This isn't very convincing for such an elementary feature of the language.

Reply via email to