0 ada
我试图使用聚合初始化一个简单的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;
如果未指定边界,则数组的下限是索引类型的下限.(你可能习惯于像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);
参考手册说明:
如果数组类型的最终祖先由unconstrained_array_definition定义,则结果的下限是左操作数的下限.
选择具有所需下限的索引子类型更为清晰.
| 归档时间: | 
 | 
| 查看次数: | 697 次 | 
| 最近记录: |