Reputation: 149
The following source code line in Ada,
type Airplane_ID is range 1..10;
, can be written as
type Airplane_ID is range 1..x;
, where x is a variable? I ask this because I want to know if the value of x can be modified, for example through text input. Thanks in advance.
Upvotes: 9
Views: 6353
Reputation: 11
As the other answers have mentioned, you can declare ranges in the way you want, so long as they are declared in some kind of block - a 'declare' block, or a procedure or function; for instance:
with Ada.Text_IO,Ada.Integer_Text_IO;
use Ada.Text_IO,Ada.Integer_Text_IO;
procedure P is
l : Positive;
begin
Put( "l =" );
Get( l );
declare
type R is new Integer range 1 .. l;
i : R;
begin
i := R'First;
-- and so on
end;
end P;
Upvotes: 1
Reputation: 4198
Can
type Airplane_ID is range 1..x;
be written where x is a variable? I ask this because I want to know if the value of x can be modified, for example through text input.
I assume that you mean such that altering the value of x alters the range itself in a dynamic-sort of style; if so then strictly speaking, no... but that's not quite the whole answer.
You can do something like this:
Procedure Test( X: In Positive; Sum: Out Natural ) is
subtype Test_type is Natural Range 1..X;
Result : Natural:= Natural'First;
begin
For Index in Test_type'range loop
Result:= Result + Index;
end loop;
Sum:= Result;
end Test;
Upvotes: 4
Reputation: 263227
No, the bounds of the range both have to be static expressions.
But you can declare a subtype with dynamic bounds:
X: Integer := some_value;
subtype Dynamic_Subtype is Integer range 1 .. X;
Upvotes: 9