我正在尝试使用聚合初始化一个简单的Ada数组,我希望编译器确定数组边界。但是,当尝试使用下面的Test_2时,我不能简单地使用整数下标。有没有办法允许编译器确定数组边界数组,然后使用简单的" Test_2(0)"符号
我正在使用gnat。
感谢。
with Interfaces; use Interfaces;
procedure Test_Init is
type U16_a is array(Integer range <>) of Unsigned_16;
-- array aggregate initialization
Test_1 : U16_a(0..1) := (16#1234#, 16#5678#); -- ok, but...
Test_2 : U16_a := (16#8765#, 16#4321#); -- let compiler create bounds
Test_3 : Unsigned_16;
begin
-- Test_1 obviously works
Test_3 := Test_1(0);
-- warning: value not in range of subtype of "Standard.Integer" defined at line 8
-- This produces a constraint.
-- What is the subtype that is defined at line 8? It is not Integer (0..1)
Test_3 := Test_2(0);
-- this works though
Test_3 := Test_2(Test_2'First);
-- and this works
Test_3 := Test_2(Test_2'Last);
-- and this works
Test_3 := Test_2(Test_2'First + 1);
end Test_Init;
答案 0 :(得分:6)
如果您没有指定边界,则数组的下限是索引类型的下限。 (您可能习惯于像C这样的语言,其中数组的下限始终为0
。但在Ada中并非如此。)
在这种情况下,下限为Integer'First
,可能为-2147483648
。
如果您希望数组范围从0
开始,则可以使用子类型Natural
:
type U16_a is array(Natural range <>) of Unsigned_16;
或者您可以使用子类型Positive
将数组的下限设置为1
。
您还可以指定每个元素的索引:
Test_2 : U16_a := (0 => 16#8765#, 1 => 16#4321#);
但这可能不会扩展;如果有大量元素,则必须为每个元素指定索引,因为位置关联不能遵循命名关联。
您可以使用数组连接来指定第一个索引,而不是使用位置或命名聚合初始值设定项:
Test_3 : U16_a := (0 => 0) & (1, 2, 3, 4, 5, 6, 7);
参考手册指出:
如果数组类型的最终祖先是由a定义的 unconstrained_array_definition,然后是结果的下限 左操作数的那个。
选择具有所需下限的索引子类型更清晰。