I have a static size array of length 1, which I try to assign a value at index 0.
void main() {
int length = 0;
int[1] arr;
arr[0] = 1;
arr[length] = 2;
}
With the above code, I get a runtime error of
Error: ArrayBoundsError array.d(6)
which cooresponds the line: arr[length] = 2.
Why does the constant 0 work, but the variable with value 0 not work?
lengthhas a special meaning inside index/slice expressions – it does the same thing as$(the length of the array being indexed/sliced). Thus,arr[length]will always result in anArrayBoundsError.Note:
lengthis deprecated in D2, and both D1 and D2 will issue a warning (when warnings are enabled):array 'length' hides other 'length' name in outer scope.