Domanda

In Ada, we can take an array slice of any array, including a String, using a range. For example:

Name( 1 .. 3 )

We can also use a range in a for loop:

for I in 1 .. 10 loop
  --do something
end loop;

Or, we could iterate over an array as follows:

for I in X'Range loop
  X(I) := Function_Call;
end loop;

So, my current line of thinking is that a range in the form "1 .. 3" would be a Range literal, much like "3" is an integer literal, and X'Range is a property that returns the range of indexes in the array X (or similarly, some ordered type X, such as an integer or enum).

At the moment, I have some code that looks like this:

Name( 1 .. 3 )

I've always felt that magic numbers like that aren't a good idea, so I suppose I could define two constants:

Name_Prefix_Range_Begin : constant Integer := 1;
Name_Prefix_Range_End   : constant Integer := 3;

and then do this:

Name( Name_Prefix_Range_Begin .. Name_Prefix_Range_End )

However, I feel it would be much cleaner if it were possible to have a constant of type Range, and just write the following to get my array slice:

Name ( Name_Prefix_Range )

So, finally, after all that, is it possible to declare either a variable or constant that can store a range? How is it written? I have made guesses which don't compile, and have not been able to find any reference to this possibility.

È stato utile?

Soluzione

Slices, and some other constructs that take ranges, can also take subtype names.

subtype Name_Prefix_Range is Integer range 1 .. 3;

and then you can use

Name (Name_Prefix_Range)

as well as

for I in Name_Prefix_Range loop
    ...
end loop;

In the language syntax, you can use a subtype name like this anywhere a discrete_range is needed. The syntax of slices in RM 4.1.2 uses it.

Note that when I say "subtype name", this includes a "type name" defined by a type declaration; the name is technically a "first subtype" name. So it's syntactically legal to say

Name (Integer)

but you will get a Constraint_Error at runtime. More legitimate would be to do something like this:

for B in Boolean loop ...
for Ch in Character loop ...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top