9

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.

J. C. M. H.
  • 159
  • 1
  • 9

4 Answers4

9

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;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Thank you so much. But in the example that you put, the value of X can be modified through text input, or it should be constant? – J. C. M. H. Dec 10 '11 at 02:37
  • 2
    The bounds in a subtype declaration can be any arbitrary expressions, as long as they're of the appropriate type. – Keith Thompson Dec 10 '11 at 02:46
  • 1
    @Shark8's answer makes a good point. When you declare `Dynamic_Subtype` as above, `X` is evaluated when the declaration is evaluated. Modifying `X` later doesn't affect the subtype. – Keith Thompson Dec 11 '11 at 00:03
4

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;
Shark8
  • 4,095
  • 1
  • 17
  • 31
3

No. An Ada range declaration must be constant.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

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;