Delphi basic tutorial graphic version of compound data types (sub-boundary)

My personal understanding is that the sub-world type is more suitable for the definition of the scope. For example, people’s age is generally 1 to 120 years old, the number of months in a year is 1 to December, and the number of days in a month is 1 to 31 days, etc. Wait.

If the value range of the variables used can be specified in the program, it will be easier to check out those illegal data, which can better ensure the correctness of the program and save memory space to a certain extent.

The sub-world type can solve the above problems well. In fact, in the definition of arrays, sub-boundary types are often used to specify the range of array subscripts.

This is a data type unique to Delphi, at least in my cognition that other languages ​​do not have

definition

type

子界类型标识符=常量1..常量2

The constant 1 is called the lower bound of the subboundary, and the constant 2 is called the upper bound of the subboundary; the so-called upper bound is also the beginning boundary, and the lower bound is the ending boundary

Note: lower and upper bounds must be the same type of sequence (called the subrange type base type), and the serial number must be greater than the upper bound lower bound number. E.g

type
    age=1..100;
    letter='a' ..'z';

Of course, similar to the aforementioned enumeration type, it can also combine type declaration and variable declaration into one step. You can define the subrange type directly in the variable description.

type
    letter='a'..' z ';
var
    ch1,ch2:letter;

Can be combined into:

var
    ch1,ch2:'a'..'d';

Algorithm

The operation rules that can use the base type also apply to the sub-boundary type of that type . For example, where you can use integer variables, you can also use sub-boundary data with integer as the base type. The operation rules for the base type are also applicable to the subboundary types of that type. For example, div, mod requires that the data participating in the operation be integer, so it can also be any sub-range type data of integer type. Data of different sub-world types with the same base type can be mixed. For example: with the following instructions:

var  x:1..100;
   y:1..500;
   z:1..1000;
    a:integer;

Legal statement:a:=Sqr(x)+y+z; z:=x+y

y:=x+z+a; When the value of x+y+a is within the range of 1~500, it is legal, otherwise an error will occur.

Application examples

Example 1. Determine the current day of the week

  procedure TForm1.Button1Click(Sender: TObject);
var
  Week: 1 .. 7;
begin

  case Week of
    1:
      ShowMessage('周一');

    2:
      ShowMessage('周二');

    3:
      ShowMessage('周三');

    4:
      ShowMessage('周四');

    5:
      ShowMessage('周五');

    6:
      ShowMessage('周六');

    7:
      ShowMessage('周日');

  else begin ShowMessage('非法')
    end;
  end;
end;

Guess you like

Origin blog.csdn.net/farmer_city/article/details/111221369