Error: ArrayBoundsError when using a variable

I have a static size array of length 1, which I am trying to assign a value with 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

 Error: ArrayBoundsError array.d(6) 

which binds the string: arr [length] = 2.

Why does the constant 0 work, but the variable with the value 0 does not work?

+4
source share
1 answer

length has a special meaning inside index / slice expressions - it does the same as $ (the length of the array is indexed / sliced). Thus, arr[length] will always have the value ArrayBoundsError .

Note: length deprecated in D2, and both D1 and D2 will give a warning (when warnings are turned on): array 'length' hides other 'length' name in outer scope .

+4
source

Source: https://habr.com/ru/post/1380099/


All Articles