Search code examples
d

What is the default type of loop index variables in D?


I have started out learning D, and I am having some trouble with the examples provided in the book The D Programming Language by Andrei Alexandrescu. A few of the examples don't compile because of casts between int and ulong types, one of which I outline below.

I suspect that the problem is caused because I am using a 64 bit version of the compiler (Digital Mars 2.064.2 for 64-bit Ununtu), and the examples in the book were tested with a 32 bit compiler.

The following code:

#!/usr/bin/rdmd
import std.stdio;
void main(){
    int[] arr = new int[10];
    foreach(i, ref a; arr)
        a = i+1;
    writeln(arr);
}

fails with the following compiler error

bcumming@arapiles:chapter1 > ./arrays.d 
./arrays.d(9): Error: cannot implicitly convert expression (i + 1LU) of type ulong to int
Failed: 'dmd' '-v' '-o-' './arrays.d' '-I.'

I can fix this by explicitly declaring the variable i to be of type int:

foreach(int i, ref a; arr)
    a = i+1;

What are the rules that determine what the default type of a loop index will be in D? Is it because I am using a 64 bit compiler?


Solution

  • The default loop index type is the same as array.length: size_t. It is aliased to uint on 32 bit, and to ulong on 64 bit.