2015-01-05 45 views
0

我想使用聚合初始化一個簡單的Ada數組,並且我希望編譯器確定數組邊界。但是,當嘗試使用下面的Test_2時,我不能簡單地使用整數下標。有沒有辦法允許編譯器確定數組邊界數組,然後使用簡單的「Test_2(0)」符號訪問它們?Ada數組聚合初始化

我正在使用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; 

回答

6

如果不指定邊界,則數組的下限是索引類型的下限。 (您可能習慣於像C,其中數組總是有下界0語言。這不是在阿達的情況。)

在這種情況下,下限爲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定義,那麼結果的下界是 左邊的操作數。

選擇具有所需下限的索引子類型更爲簡潔。

+0

或指定聚集中的邊界,如下所示:'Test_2:U16_a:=(0 => 16#8765#,1 => 16#4321#);' – egilhh

+0

@egilhh:是的,但那不規模也是如此。如果您有大量元素,則必須爲每個元素指定索引,因爲位置關聯不能跟隨命名關聯。 –

+0

當然,但你可能會從文件中讀取數組元素 – egilhh