Chris:

The following:

import std.stdio;

void main() {
  int[5] arg;
arg[10] = 3; // Compiler says (of course): Error: array index 10 is out of bounds arg[0 .. 5]
}

import std.stdio;

void main() {
  int[5] arg;
  foreach (i; 0..10) {
    arg[i] = i;
  }
}

Compiler says nothing, but we get a runtime error 'Range violation'.

Bug or design?

Spotting the second bug is beyond the very limited analysis capabilities of the D compiler. But a slightly different but still rather common kind of code (where the index is not mutable) could be spotted as buggy by the compiler:


void main() {
    int[5] data;
    foreach (const i; 0 .. 10)
        data[i] = 0;
    foreach (immutable i; 0 .. 10)
        data[i] = 0;
    int[10] big;
    foreach (const i, x; big)
        data[i] = x;
}

(In D it's very good to tag as const/immutable the indexes of arrays, as work around a design bug of D foreach).

But the compiler must recognize this as correct code:


void main() {
    int[5] data;
    foreach (const i; 0 .. 10)
        if (i < 5)
            data[i] = 0;
}


So can we add this logic in the compiler?

Bye,
bearophile

Reply via email to