On Thursday, 13 December 2012 at 04:11:10 UTC, Pacoup wrote:
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.

Dynamic arrays are arrays whose length is set at run time. Thus, it makes sense that they would give a run time error when they fail.

Plus, trying to determine whether the length of an array is exceeded at compile-time would be a hard problem. Sure, in this instance it's easy to see that the length of the array is exceeded... but then again, you aren't doing anything you couldn't use a static array for either.

Consider:

void main() {
   int[] arr;
   foo(arr);
   arr[0] = 2;
}

Should this spit out a compile time error? You can't say without knowing what 'foo' does. If I say foo means this:

void foo(int[] array) {
   int len;
   readf(" %s", &len);
   array.length = len;
}

Well, now it depends on what len is. This could easily be reading from a file where you know len is always greater than 0, but the compiler doesn't know. So does it fail to compile until you put some pragmas in to assure the compiler that its going to be okay... or what?

Of course, regardless, you're going to need it to throw an exception if you're wrong because things change and you might read in a bad file that sets len to 0.

In general, the compiler can't know ahead of time whether accessing a dynamic array will be out of bounds without running it. Exceptions are designed to handle these types of programming errors.

Reply via email to