gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:17:14 24 4
gpt4 key购买 nike

我已经开始学习 D,但我在使用 Andrei Alexandrescu 所著的 The D Programming Language 一书中提供的示例时遇到了一些麻烦。由于 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);
}

因以下编译器错误而失败
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 为 int 类型来解决这个问题:
foreach(int i, ref a; arr)
a = i+1;

确定 D 中循环索引的默认类型的规则是什么?是因为我使用的是 64 位编译器吗?

最佳答案

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

关于d - D 中循环索引变量的默认类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com