Урок 11. Типы в PascalABC.NET. Создание своего типа


Типы

Приветствуем тебя, юный (или не очень юный) читатель нашего сайта! Сегодня мы с вами поговорим про типы в PascalABC.NET: числовые, символьные и логические. Они немного отличаются от стандартных типов Turbo Pascal.

Давайте вспомним какими могут быть величины? Об этом говорилось в отдельной статье. Сейчас мы быстренько все впомним. Любая величина может быть трех типов: числовой, символьной и логическй. Раньше мы использовали всего несколько типов (integer, real, boolean ), но пришло время расширить знания.

Типы

Все типы я буду оформлять в удобную табличку, хотя некоторые моменты буду пояснять. Таблица будет иметь три столбца: тип, размер в байтах, дапозон значений.

Важно! Все диапазоны и типы действительны только для PascalABC.NET, во Free Pascal и Turbo Pascal у этих типов будут другие значения. Например, в  PascalABC.NET тип integer имеет диапазон от -2147483648 до 2147483647, а в Turbo Pascal  у этого типа диапазон  от -32768 до 32767.

Числовые типы

Принято разделять числовые типы на две большие подгруппы: целые и вещественные.

Целые типы

Тип Размер в байтахДиапазон значений
shortint1-128..127
smallint2-32768..32767
integer, longint4-2147483648..2147483647
int648-9223372036854775808..9223372036854775807
byte10..250
word20..65535
longword, cardinal40..4294967295
uint6480..18446744073709551615

Вещественные типы

Тип Размер в байтахДиапазон значенийКоличесвто значащих цифр
real8-1.8∙10308.. 1.8∙1030815-16
double8-1.8∙10308.. 1.8∙1030815-16
single4-3.4∙1038.. 3.4∙10387-8

Для удобства в Паскале заведены специальные константы, которые возвращают на свое место минимальное или максимальное значение разных типов. Ниже вы можете посмотреть таблицу, в которую занесены все константы.

Константа(1)Константа(2)Значение
MaxShortIntshortint.MaxValueМаксимальное значение типа shortint
MaxBytebyte.MaxValueМаксимальное значение типа byte
MaxSmallIntsmallint.MaxValueМаксимальное значение типа smallint
MaxWordword.MaxValueМаксимальное значение типа word
MaxIntinteger.MaxValueМаксимальное значение типа integer
MaxLongWordlongword.MaxValueМаксимальное значение типа longword
MaxInt64int64.MaxValueМаксимальное значение типа int64
MaxUint64uint64.MaxValueМаксимальное значение типа uint64
MaxDoubledouble.MaxValueМаксимальное значение типа double
MinDoublereal.EpsilonМинимальное значение типа double
MaxRealreal.MaxValueМаксимальное значение типа real
MinRealreal.EpsilonМинимальное значение типа real
MaxSinglesingle.MaxValueМаксимальное значение типа single
MinSinglesingle.EpsilonМинимальное значение типа single

Логический тип

В PascalABC.NET  только один логический тип — boolean. Про него была написана целая статья. Тип Boolean принимает значение true или false, и его размер — 1 байт.

Символьный тип и строки

Символьный тип

Символьный тип char занимает 2 байта и хранит Unicode-символ.

Чтобы не писать отдельную  статью про символьный тип, вкратце расскажу про него здесь. В   PascalABC.NET помимо стандартных функций chr  и ord, добавлены новые функции — ChrUnicode и OrdUnicode.

Chr(n) — функция, возвращающая символ с кодом n в кодировке Windows;
Ord(с) — функция, возвращающая значение типа byte, представляющее собой код символа c в кодировке Windows.

ChrUnicode(w) — возвращает символ с кодом w в кодировке Unicode;
OrdUnicode(с) — возвращает значение типа word, представляющее собой код символа c в кодировке Unicode.

Давайте поэкспериментируем, составим вот такую небольшую программку.

program Chr_Ord_Example;

begin
  writeln(ChrUnicode(30000));
  writeln(OrdUnicode('*'));
  writeln(Chr(42));
  writeln(Ord('*'));
end.

Этой программой я хочу проверить накладываются ли друг на друга кодировка Windows  и Unicode. Ниже, на скриншоте вы можете посмотреть результат работы программы.

Символьный тип в Паскаль
Накладываются. Просто Unicode длиннее, чем кодировка Windows.

Строковой тип

Строки имеют тип string, состоят из набора последовательно расположенных символов char и используются для представления текста.

Строки могут иметь произвольную длину.  Строки изменяемы.

Наверное, сейчас вы сомневаетесь в том, что в PascalABC.NET строки могут быть произвольной длины. Давайте проверим это с помощью небольшой программы.

program String_Example;

label m1;
begin
  var s: string; {Так как мы с вами работает в PascalABC.NET, то данная конструкция здесь не является ошибкой.}
  var n := 0; 
  s := 'HelluuHelluuuuuuuulluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! Helluuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!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uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuo! HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuo! HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuoHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuo! HelluuHelluuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo! uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo!';
  writeln(Length(s)); {Функция length() возвращает длину строки.}
  m1: {ставим метку}
  s := s + s; {В программировании операция сложения, выполненная со строками, называется конкатенацией}
  Inc(n);
  if n < 11 then goto m1;
  writeln(Length(s));
end.

Строковой тип

Кроме того, в PascalABC.NET реализованы размерные строки. Для их описания используется тип string[n], где n — константа целого типа, указывающая длину строки.

Перечислимый и диапазонный типы

Перечислимый тип

Перечислимый тип определяется упорядоченным набором идентификаторов. Чтобы объявить  новый тип, используется специальное слово — type. Его необходимо ставить перед var.

type
  typeName = (value1, value2,..., valueN);

Значения перечислимого типа занимают 4 байта. Каждое значение value представляет собой константу типа typeName, попадающую в текущее пространство имен.

Например:

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

К константе перечислимого типа можно обращаться непосредственно по имени, а можно использовать запись typeName.value, в которой имя константы уточняется именем перечислимого типа, к которому она принадлежит:

var
  a, b: month;

begin
  a := February;
  b := Month.August;
end.

Для значений перечислимого типа можно использовать функции Ord, Pred и Succ, а также процедуры Inc и Dec (Подробнее про эти функции и процедуры). Функция Ord возвращает порядковый номер значения в списке констант соответствующего перечислимого типа, нумерация при этом начинается с нуля.

program type_example;

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

var
  a, b: month;

begin
  a := February;
  b := Month.August;
  writeln(a,', ', b);
  Inc(a);
  b := pred(b);
  writeln(a,', ', b);
  writeln(Ord(a),', ', Ord(b));
end.
Перечисляемый тип
Результат работы программы

Диапазонный тип

Диапазонный тип представляет собой подмножество значений целого, символьного или перечислимого типа и описывается в виде a..b, где a — нижняя, b — верхняя граница интервального типа, a<b.

Пример.

program type_example;

type
  Month = (January, February, March, April, May, June, July, August, September, October, November, December);

var
  a : January..May;
  b : 1..10;
  c : 'a'..'z';

begin
  a := March;
  b := 2;
  c := 'b';
  b := pred(b);
  writeln(a,', ', b,', ', c);
end.
Диапазонный тип
Результат работы программы

Тип, на основе которого строится диапазонный тип, называется базовым для этого диапазонного типа. Значения диапазонного типа занимают в памяти столько же, сколько и значения соответствующего базового типа.

На сегодня все! Урок получился объемным, но, надеюсь, понятным. Если же у вас возникли вопросы, напишите нам.

  1. Суперский сайт.
    С 6 класса мечтал стать программистом
    И выучить программные языки.
    Этот сайт лучший ,все понятно.

  2. Отличный сайт для новичков в программировании, спасибо!
    По поводу перечислимого типа: я так понял, что в Паскале, как и во многих других ЯП, счет в упорядоченных типах множеств начинается с 0 (а не с 1). Мне кажется стоит добавить комментарий об этом в текущую статью, т.к. новички могут не понять почему ord(a) / March — имеет индекс 2, а ord(b) / July — имеет индекс 6.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *