www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Array-bound indexes

I keep a list of my bugs, in years some of my bugs has come from using an index
on the wrong array and relates mistakes.

D avoids several of those C bugs using the foreach syntax, that keeps the code
more DRY and removes the possibility of some mistakes:

This is the cleaner and safer:
foreach (x; array) {

This is safe still:
foreach (i, ref item; array) {

This is a bit less tidy, but better than the C for loop still:
foreach (i; 0 .. array.length) {


But in some situations (even when foreach is used) the algorithm is fiddly and
not simple. In such situations an annotation to tie an index to the indexes
domain of a specific array may help:

auto arr1 = new int[5];
 domain(arr1) int i;
auto arr2 = new int[5];
 domain(arr2) int j;

i is bounded in 0 .. arr1.length
j is bounded in 0 .. arr2.length

arr1[i] = 0; // compiles
arr1[j] = 0; // compile-time error, because j is the index of arr2
arr1[i + 1] = 0; // compiles, unless inferred as out of bounds
arr1[i + j] = 0; // compiles, unless inferred as out of bounds

I don't know how much useful this may be.
Bye,
bearophile
Oct 31 2010