Subrange types

This is an old revision of Subrange types, edited by Thaddy at . The current revision is 136458.

Back to data types.

Range of values: Corresponds to the definition defined by yourself

Storage requirements: Corresponds to the underlying basic data type

A subrange type:

Assigning other values ​​leads to compiler error messages when the program is compiled and the compilation process is aborted. That is, the executable program is not created.

There are two ways to define subrange types.

Variant 1:

var
  // Defines an integer subrange type
  // in the range of 10 to 123
  tbNumber1 : 10 .. 123;

  // Defines a character subrange type
  // in the range of A to Z (all uppercase)
  tbLetter1 : 'A' .. 'Z';

Variant 2:

Type
  // Defines an integer subrange type
  // in the range of 10 to 123
  TNumber2 = 10 .. 123;

  // Defines a character subrange type
  // in the range of A to Z (all uppercase)
  TLetter2 = 'A' .. 'Z';

var
  tbNumber2 : TNumber2 ;
  tbLetter2 : TLetter2 ;

Examples of assigning valid values:

  tbNumber1 := 10;
  tbNumber1 := 123;
  tbNumber2 := 10;
  tbNumber2 := 123;
  tbLetter1 := 'F';
  tbLetter2 := 'F';

Examples of assigning invalid values:

  // the values are outside the subrange
  tbNumber1 := 9;
  tbNumber2 := 124;
  tbLetter1 := 'f';
  tbLetter2 := 'f';
  // the values ​​are string literals
  tbNumber1 := '10';
  tbNumber1 := '123';
  tbNumber2 := '10';
  tbNumber2 := '123';

Example of how to uses ranges for loop variables.

This can improve readability and maintainability of your code.
The example avoids using for x:=y to z do and instead uses a for in do pattern. It helps to avoid common indexing mistakes like 1 to 4 instead of 0 to 3, etc.

type
  myrange = 1..4;
var
  arr:array[myrange,myrange] of integer = (
    (1, 2, 3, 4),
    (2, 3, 1, 4),
    (3, 1, 2, 4),
    (4, 2, 1, 3)
  );

  i,j:integer;
begin
  for i in myrange do
  begin
    for j in myrange do
      write(arr[i,j]:2);
    writeln;
  end;
end.