D中循环索引变量的默认类型是什么?

bcu*_*ing 4 d

我已经开始学习D了,我对Andrei Alexandrescu 所着的D编程语言中提供的例子有些麻烦.由于int和ulong类型之间的转换,一些示例无法编译,其中一个我在下面概述.

我怀疑问题是由于我使用64位版本的编译器(Digital Mars 2.064.2 for 64-bit Ununtu)引起的,本书中的示例是使用32位编译器测试的.

以下代码:

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

因以下编译器错误而失败

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.'
Run Code Online (Sandbox Code Playgroud)

我可以通过明确声明变量i为int类型来解决这个问题:

foreach(int i, ref a; arr)
    a = i+1;
Run Code Online (Sandbox Code Playgroud)

有哪些规则可以确定循环索引的默认类型在D中?是因为我使用的是64位编译器吗?

Orv*_*ing 6

D中的所有索引都是类型size_t.这是目标上指针的大小.


Ada*_*ppe 6

默认循环索引类型与array.length:相同size_t.它在32位上为uint,在64位上为ulong.