J. C. M. H.
J. C. M. H.

Reputation: 149

About "range" in Ada

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

Answers (4)

Graham Stark
Graham Stark

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

Shark8
Shark8

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

Mitch Wheat
Mitch Wheat

Reputation: 300529

No. An Ada range declaration must be constant.

Upvotes: 3

Keith Thompson
Keith Thompson

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

Related Questions