Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 403
bcumming Avatar asked Dec 16 '22 04:12

bcumming


2 Answers

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.

like image 124
Adam D. Ruppe Avatar answered Jan 14 '23 20:01

Adam D. Ruppe


All indexes in D are of the type size_t. This is the size of a pointer on the target.

like image 32
Orvid King Avatar answered Jan 14 '23 20:01

Orvid King