Kevin
Kevin

Reputation: 530

Size of array type in Ada

I'm just getting back into Ada after being away for quite a while, so this is probably a beginner question. Essentially I'm trying to print the length of a 1-dimensional array. This array is inside of a record. I can print the type fine if I make an instance of the record but I feel there must be a way to print the length from just the type alone. Here a very contrived example of some code I thought would work:

with Ada.Text_Io;

procedure TestApp is
   type int_array is array (integer range <>) of integer;
   type item_type is record
      ia : int_array (0 .. 20);
   end record;
begin
   Ada.Text_Io.Put_Line(Integer'image(item_type.ia'length));
end TestApp;

but I get the error "Invalid prefix in selected component 'item_type'". If I instantiate item_type and get the range from that it of course works fine but I feel I must be missing something.

Thanks

Upvotes: 0

Views: 4862

Answers (1)

egilhh
egilhh

Reputation: 6430

This:

   ia : int_array (0 .. 20);

is an anonymous array subtype, and the only way to get the length of an anonymous array is through an object (since there is no name to designate the type). You can however declare the array subtype explicitly (a named subtype):

with Ada.Text_Io;

procedure TestApp is
   type int_array is array (integer range <>) of integer;

   subtype sub_int_array is int_array(1..20);

   type item_type is record
      ia : sub_int_array;
   end record;
begin
   Ada.Text_Io.Put_Line(Integer'image(sub_int_array'length));
end TestApp;

Upvotes: 3

Related Questions